Ruby 在 Rails 上:与 "has_many" 的关系

Ruby on Rails : relationship with "has_many"

X 先生只喜欢 Y 先生post制作的一个

如何在 X 先生和 Y 先生之间建立关系以查看 Y 先生的 post? (查看建议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

我应该使用 uniq 吗?

我不是 100% 确定你是不是这个意思,但如果你想将 UserPostLike 联系起来,请按以下步骤操作:

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

您必须添加相应的数据库迁移才能将属性添加到 likes