2011-05-13 51 views
0

是否有可能從下列查詢創建named_scope:多在範圍/ 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或導軌聯接3範圍?

感謝

回答

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 
+0

感謝mosch,所以控制器看起來像@gigs = User.find(1).my_scope? – pingu 2011-05-13 14:13:59