ruby on rails - Assiging model reccord to more than one user -
i'm working on rails app , 1 of features lets give virtual gifts other users.
one user gives gift(through gift model) user. 1 user giver(gift.giver) other user receiver (gift.receiver)
my question how assign each gift 2 users, giver , receiver, can later call user.gifts_received list of gifts user received , user.gifts_given list of gifts user gave?
is better have user.gifts instead of user.gifts_received , user.gifts_given? plan on using acts_as_follower gem let users see gifts given , received users follow.
in past apps, when user created post, post belonged 1 user, assigned with:
@post.user = current_user
and how use acts_as_follower gem gifts 1 user user follows?
i guessing gift model looks this:
gift.rb
class gift < activerecord::base belongs_to :giver, class_name: 'user' belongs_to :receiver, class_name: 'user' ... end
so this, need make user model this, acts_as_follower stuff added:
user.rb
class user < activerecord::base has_many :given_gifts, class_name: 'gift', foreign_key: 'giver_id' has_many :received_gifts, class_name: 'gift', foreign_key: 'receiver_id' acts_as_followable acts_as_follower ... end
you need these part of gift migration:
f.integer :receiver_id f.integer :giver_id
which gives access these methods when assigned:
giver = user.first receiver = user.last gift = gift.create(giver: giver, receiver: receiver) gift.giver => giver gift.receiver => receiver giver.given_gifts => [gift] receiver.received_gifts => [gift]
and acts_as_follower methods (using variables above):
giver.follow(receiver) gift.where(receiver_id: giver.all_following.pluck(:id)) => [gift]
where
allows pass in array of values queried against in db (which all_following
returns).
check out more information.
Comments
Post a Comment