【问题标题】:How to properly use joins on polymorphic association in Active Record如何在 Active Record 中正确使用多态关联的连接
【发布时间】:2015-11-26 09:03:08
【问题描述】:

我有一个模型Action,它有一个

belongs_to :actor, polymorphic: true

该演员可以是:CustomerAdminSellerGuest

我想将Action 的实例过滤为仅由特定SellerGuest 执行的操作。我该怎么做?

在正常的关联中,我会加入两个表,但是这样,我不知道该怎么做。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord activemodel


    【解决方案1】:

    希望这对你有帮助:-

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-25
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多