范围/ named_scope中的多个连接查询

时间:2011-05-13 13:29:27

标签: sql ruby-on-rails scope 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或rails 3范围内加入?

由于

1 个答案:

答案 0 :(得分: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