如何在Active Record中正确使用多态关联的连接

时间:2015-11-26 09:03:08

标签: ruby-on-rails ruby activerecord activemodel

我的模型Action

belongs_to :actor, polymorphic: true

该演员可以是:CustomerAdminSellerGuest

我想将Action的实例仅过滤到特定SellerGuest所做的操作。我怎么能这样做?

在正常的关联中,我会加入这两个表格,但这样,我不知道如何正确地做到这一点。

1 个答案:

答案 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'})