【问题标题】: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
该演员可以是:Customer、Admin、Seller 或 Guest。
我想将Action 的实例过滤为仅由特定Seller 或Guest 执行的操作。我该怎么做?
在正常的关联中,我会加入两个表,但是这样,我不知道该怎么做。
【问题讨论】:
标签:
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'})