Rails查询内部联接

时间:2012-06-29 14:32:11

标签: ruby-on-rails ruby ruby-on-rails-3 inner-join

clients :has_many :project,:roles

我已经实施,但它不是一个好的实现..

2 个答案:

答案 0 :(得分:2)

joins可以在几个级别深度使用,例如,Activity属于Carrier     Activity.joins(:carrier => {:projects => {:client =>:roles}})

将生成

行的sql
SELECT * from activities
JOIN carriers on activities.carrier_id = carriers.id
JOIN projects on carriers.id = projects.carrier_id
JOIN clients on projects.client_id = clients.id
JOIN roles on roles.client_id = clients.id

您可以添加条件。您需要对列名称进行限定,即使用projects.id而不是id,以便您的数据库知道您想要的id

答案 1 :(得分:0)

你的解决方案已经足够好了。也许你可以像这样改进它:

clients = Client.joins(:roles).where("roles.name in ('responsible', 'replacement')")
client_ids = clients.map(:&id)
projects = Project.where('id in (?) && start=? && stop=?',client_ids,params[:start_time],params[:end_time])
project_ids = projects.map(:&id)
carriers = Carrier.joins(:projects).where('projects.id in (?) AND carriers.has_clients=1', project_ids)
carrier_ids = carriers.map(&:id)
activities = Activity.joins(:carriers).where('carriers.id in (?)', carrier_ids)