2014-03-12 59 views
0

我有以下型号:氩多个连接

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 
+0

请在上面的代码中指定用户模型关系。 –

回答

1

您可以使用一组嵌套的joins方法,如这样的:

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

请注意,我现在用的是=>符号,但是你可以使用红宝石1 .9+也是。

+0

出现错误** ActiveRecord :: ConfigurationError:未找到名为'products'的关联;也许你拼错了吗?** –

+0

然后试试':product'。这是一种“belongs_to”关系。 – MurifoX

+0

得到另一个错误** ActiveRecord :: ConfigurationError:未找到名为'producer'的关联;也许你拼错了吗?** –