定义自定义has_many关系

时间:2017-09-19 16:13:24

标签: activerecord ruby-on-rails-5

我们假设某个应用程序的User可以Like一个Post。但Post也可以拥有Userowner_id)。所以模型看起来像

class User < ApplicationRecord
  has_many :likes
  has_many :posts, through: :likes
end

class Like < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

class Post < ApplicationRecord
  has_many :likes
  has_many :users, through: :likes
  belongs_to :owner, class_name: 'User'
end

如何定义一个关系,该关系会返回与帖子有任何关联的所有用户?

因此尝试替换users关联:

class Post < ApplicationRecord
  # no owner_id, lambda is called in an User::ActiveRecord_Relation context
  has_many :users, -> { where('users.id = ? OR likes.post_id = ?', owner_id, id) }, through: :likes

  # doesn't work because "Relation passed to #or must be structurally compatible."
  def users
    User.where(id: owner_id).or(users)
  end

  # works but isn't an association.
  def users
    User.joins(:likes).where('users.id = ? OR likes.post_id = ?', owner_id, id)
  end
end

我希望能够定义允许我写的东西

Post.includes(:users)

ActiveRecord::AssociationNotFoundError: Association named 'users' was not found on Post; perhaps you misspelled it?

0 个答案:

没有答案