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

cia*_*ben 4 ruby activerecord ruby-on-rails activemodel

我有一个模型Action,有一个

belongs_to :actor, polymorphic: true
Run Code Online (Sandbox Code Playgroud)

这演员可以是:一CustomerAdminSellerGuest

我想将 的实例过滤Action为仅由特定SellerGuest. 我怎样才能做到这一点?

在正常关联中,我会加入两个表,但是这样,我不知道如何正确执行。

use*_*853 5

希望这对你有帮助:-

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
Run Code Online (Sandbox Code Playgroud)

然后这样称呼它:-

Action.by_type(Seller).to_sql
=> "SELECT \"actions\".* FROM \"astions\" JOIN sellers ON sellers.id = actions.actorable_id AND actions.actorable_type = 'Seller'" 
Run Code Online (Sandbox Code Playgroud)

或者您可以通过以下方式实现:-

belongs_to :actor, :foreign_key => :actorable_id, polymorphic: true

Action.joins(:actor).where('actors.actorable_id = ? AND actors.actorable_type = ?', seller_id, 'Seller'})
Run Code Online (Sandbox Code Playgroud)