简体   繁体   中英

Translate SQL query to Ruby

Just need help translating this SQL query to Ruby. I'm on rails 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). It is a library that maps Ruby objects to a relational database (thus, Object Relational Mapping library, or 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:

AbTemplates.joins(:ab_splits).group(:AS_templateId).count

You will get a hash with template ID as key, and count as value.

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) ):

class Split < ActiveRecord::Base
  belongs_to :template
end

class Template < ActiveRecord::Base
  has_many :splits
end

Template.joins(:splits).group(:template_id).count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM