Multiple join query in a scope/named_scope
Is it possible to create a named_scope from the following query:
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 gi开发者_JS百科gs g ON bg.gid = g.id
WHERE u.id = 1
I am struggling to do it, is it possible to represent multiple :joins in a named_scope or rails 3 scope?
Thanks
Yes, this can be done with:
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
精彩评论