cia*_*ben 4 ruby activerecord ruby-on-rails activemodel
我有一个模型Action,有一个
belongs_to :actor, polymorphic: true
Run Code Online (Sandbox Code Playgroud)
这演员可以是:一Customer,Admin,Seller或Guest。
我想将 的实例过滤Action为仅由特定Seller或Guest. 我怎样才能做到这一点?
在正常关联中,我会加入两个表,但是这样,我不知道如何正确执行。
希望这对你有帮助:-
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)
| 归档时间: |
|
| 查看次数: |
2711 次 |
| 最近记录: |