Kevin77 Kevin77 - 19 days ago 6
Ruby Question

Ruby on Rails : relationship with "has_many"

Mr X likes only one post made by Mr Y

How can I create a relationship between Mr X and Mr Y to see the Mr Y's posts? (to see the suggested posts)

user.rb

has_many :posts
has_many :liked_posts, through: :liked, source: :post


post.rb

def liked_by?(user)
likes.where(user: user).any?
end


likes.rb

# id :integer not null, primary key
# user_id :integer not null
# like_id :integer not null


Should I use uniq ?

Answer

I'm not 100% certain if you mean this, but in case you want to relate User with Post through Like then proceed as:

user.rb

has_many :posts
has_many :likes
has_many :liked_posts, through: :likes

post.rb

has_many :likes

def liked_by?(user)
  self.likes.where(user: user).any?
end

likes.rb

belongs_to :user
belongs_to :post

You'd have to add the respective database migrations to add the attributes to likes

Comments