我们假设某个应用程序的User
可以Like
一个Post
。但Post
也可以拥有User
(owner_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?