我有以下模型:
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
您可以像这样使用嵌套的joins
方法集:
Favorite.joins(:product => [:producer , :distributor]).where("favorites.user_id = 1")
请注意,我使用的是=>
符号,但你也可以使用ruby 1.9+符号。