我的模型Action
有
belongs_to :actor, polymorphic: true
该演员可以是:Customer
,Admin
,Seller
或Guest
。
我想将Action
的实例仅过滤到特定Seller
或Guest
所做的操作。我怎么能这样做?
在正常的关联中,我会加入这两个表格,但这样,我不知道如何正确地做到这一点。
答案 0 :(得分:2)
希望这对您有所帮助: -
class Action < ActiveRecord::Base
belongs_to :actor, polymorphic: true
scope :by_type, lambda { |type| joins("JOIN #{type.table_name} ON #{type.table_name}.id = #{Opinion.table_name}.opinionable_id AND #{Opinion.table_name}.opinionable_type = '#{type.to_s}'") }
end
然后称之为: -
Action.by_type(Seller).to_sql
=> "SELECT \"actions\".* FROM \"astions\" JOIN sellers ON sellers.id = actions.actorable_id AND actions.actorable_type = 'Seller'"
或者你可以通过这个来实现: -
belongs_to :actor, :foreign_key => :actorable_id, polymorphic: true
Action.joins(:actor).where('actors.actorable_id = ? AND actors.actorable_type = ?', seller_id, 'Seller'})