[英]Translate SQL query to Ruby
Just need help translating this SQL query to Ruby. 仅需要帮助将此SQL查询转换为Ruby。 I'm on rails 4.1.5
我在轨道上4.1.5
"SELECT COUNT(*) FROM ab_splits
INNER JOIN ab_templates ON ab_splits.AS_templateId = ab_templates.AB_id
GROUP BY AS_templateId"
First model: 第一个模型:
class AbSplits < ActiveRecord::Base
self.table_name = "ab_splits"
self.primary_key= :AS_id
end
Second model: 第二种模式:
class AbTemplates < ActiveRecord::Base
self.table_name = "ab_templates"
self.primary_key= :AB_id
end
Any help is appreciated. 任何帮助表示赞赏。
First of all, you're using ActiveRecord to do this (note < ActiveRecord::Base
in your model files). 首先,您正在使用ActiveRecord进行此操作(请注意模型文件中的
< ActiveRecord::Base
)。 It is a library that maps Ruby objects to a relational database (thus, Object Relational Mapping library, or ORM). 它是一个将Ruby对象映射到关系数据库的库(因此,对象关系映射库或ORM)。
You will need to tell your models a little bit about the structure of your database: 您需要向您的模型介绍一下数据库的结构:
class AbSplits < ActiveRecord::Base
self.table_name = "ab_splits"
self.primary_key = :AS_id
belongs_to :ab_template, :foreign_key => "AS_templateId"
end
class AbTemplates < ActiveRecord::Base
self.table_name = "ab_templates"
self.primary_key = :AB_id
has_many :ab_splits, :class_name => :AbSplits, :foreign_key => "AS_templateId"
end
When you do so, you can execute the following ActiveRecord query: 这样做时,您可以执行以下ActiveRecord查询:
AbTemplates.joins(:ab_splits).group(:AS_templateId).count
You will get a hash with template ID as key, and count as value. 您将获得一个以模板ID为键的哈希,并计为值。
Note that this would be much less painful if you had table, column and class names that follow The Rails Way (with tables splits (id, template_id)
and templates (id)
): 请注意,如果表名,列名和类名遵循The Rails Way(表
splits (id, template_id)
和templates (id)
),则将减轻很多麻烦:
class Split < ActiveRecord::Base
belongs_to :template
end
class Template < ActiveRecord::Base
has_many :splits
end
Template.joins(:splits).group(:template_id).count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.