Rails ActiveRecord查询使用多个连接涉及多态关联

问题描述:

我想弄清楚如何使用AR给出下面的模型定义复制下面的SQL查询。演员是执行平均的必要条件。结果集应该按照foo分组(来自多态关联)。任何帮助表示赞赏。Rails ActiveRecord查询使用多个连接涉及多态关联

SQL:

SELECT AVG(CAST(r.foo AS decimal)) "Average", s.bar 
FROM rotation r INNER JOIN cogs c ON r.cog_id = c.id 
      INNER JOIN sprockets s ON s.id = c.crankable_id 
      INNER JOIN machinists m ON r.machinist_id = m.id 
WHERE c.crankable_type = 'Sprocket' AND 
     r.machine_id = 123 AND 
     m.shop_id = 1 
GROUP BY s.bar 

ActiveRecord的模式:

class Rotation < ActiveRecord::Base 
    belongs_to :cog 
    belongs_to :machinist 
    belongs_to :machine 
end 

class Cog < ActiveRecord::Base 
    belongs_to :crankable, :polymorphic => true 
    has_many :rotation 
end 

class Sprocket < ActiveRecord::Base 
    has_many :cogs, :as => :crankable 
end 

class Machinist < ActiveRecord::Base 
    belongs_to :shop 
end 

UPDATE

,我想出了一个办法,使其工作,但感觉像作弊。有没有比这更好的方法?

Sprocket.joins('INNER JOIN cogs c ON c.crankable_id = sprockets.id', 
       'INNER JOIN rotations r ON r.cog_id = c.id', 
       'INNER JOIN machinists m ON r.machinist_id = m.id') 
    .select('sprockets.bar', 'r.foo') 
    .where(:r => {:machine_id => 123}, :m => {:shop_id => 1}) 
    .group('sprockets.bar') 
    .average('CAST(r.foo AS decimal)') 

SOLUTION

阿尔宾的回答没有工作的,是的,但也使我工作的解决方案。首先,我在Cog中错字,不得不从关系改变:

has_many :rotation 

以复数形式:

has_many :rotations 

随着到位,我可以使用下面的查询

Sprocket.joins(cogs: {rotations: :machinist}) 
    .where({ machinists: { shop_id: 1 }, rotations: { machine_id: 123}}) 
    .group(:bar) 
    .average('CAST(rotations.foo AS decimal)') 

唯一真正的区别是,我因为机器不属于机械师在where子句中分离出来。谢谢Albin!

我觉得这个代码更简单一点,并采取更多的帮助从AR

Sprocket 
.joins(cogs: {rotations: :machinist}) 
.where({ machinists: { machine_id: 123, shop_id: 1 } }) 
.group(:bar) 
.average('CAST(rotations.foo AS decimal)') 

SELECT子句是不必要的,你没有,因为你只需要他们内部查询,AR选择值帮助您决定之后需要什么。

我测试了这一点在我自己的一个项目使用类似的结构,但它是不完全一样的车型所以有可能是一个错字或东西在里面,如果它不跑直线上升。我跑:

Activity 
.joins(locations: {participants: :stuff}) 
.where({ stuffs: { my_field: 1 } }) 
.group(:title) 
.average('CAST(participants.date_of_birth as decimal)') 

生产这种查询

SELECT AVG(CAST(participants.date_of_birth as decimal)) AS average_cast_participants_date_of_birth_as_decimal, title AS title 
FROM `activities` 
INNER JOIN `locations` ON `locations`.`activity_id` = `activities`.`id` 
INNER JOIN `participants` ON `participants`.`location_id` = `locations`.`id` 
INNER JOIN `stuffs` ON `stuffs`.`id` = `participants`.`stuff_id` 
WHERE `stuffs`.`my_field` = 1 
GROUP BY title 

其中AR使得一个哈希看起来像这样:

{"dummy title"=>#<BigDecimal:7fe9fe44d3c0,'0.19652273E4',18(18)>, "stats test"=>nil} 
+0

感谢您的答复,这并没有工作完全原样是,但让我得到了一个不需要原始SQL(除了演员表)之外的工作解决方案。我会尽快用最终解决方案更新这个问题。 – Kevin 2014-11-05 18:51:46