【问题标题】:Multiple join query in a scope/named_scope范围/named_scope 中的多连接查询
【发布时间】:2011-05-13 13:29:26
【问题描述】:

是否可以从以下查询中创建 named_scope:

SELECT g.*, b.*
FROM users u 
LEFT JOIN band_users bu ON u.id = bu.uid 
LEFT JOIN bands b ON bu.bid = b.id 
LEFT JOIN bands_gigs bg ON b.id = bg.bid 
LEFT JOIN gigs g ON bg.gid = g.id
WHERE u.id = 1

我正在努力做到这一点,是否可以在 named_scope 或 rails 3 范围内表示多个 :join?

谢谢

【问题讨论】:

    标签: sql ruby-on-rails scope named-scope


    【解决方案1】:

    是的,可以这样做:

    class Band < ActiveRecord::Base
      has_and_belongs_to_many :gigs
    
      ...
    end
    
    class User < ActiveRecord::Base
      has_and_belongs_to_many :bands
    
      scope :my_scope, joins(:bands => :gigs)
      ...
    end
    

    【讨论】:

    • 感谢 mosch,所以控制器看起来像 @gigs = User.find(1).my_scope ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2015-10-06
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多