Ar多个连接

时间:2014-03-12 11:58:33

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

我有以下型号:

class Distributor < ActiveRecord::Base
  has_many :products
end

class Producer < ActiveRecord::Base
   has_many :products
end

class Product < ActiveRecord::Base
  has_one :favorite
  belongs_to :producer
  belongs_to :distributor
end

class Favorite < ActiveRecord::Base
  belongs_to :product
end

class User < ActiveRecord::Base
  has_many :favorites
end

我想构建一个AR表达式,类似于sql查询:

select *
from `favorites`
inner join `products` on `products`.`id` = `favorites`.`product_id`
inner join `producers` on `producers`.`id` = `products`.`producer_id`
inner join `distributors` on `distributors`.`id` = `products`.`distributor_id`
where `favorites`.`user_id` = 1

1 个答案:

答案 0 :(得分:1)

您可以使用嵌套的joins方法,如下所示:

Favorite.joins(:product => [:producer , :distributor]).where("favorites.user_id = 1")

请注意,我使用的是=>表示法,但您也可以使用ruby 1.9+表示法。