简体   繁体   English

ROR关联按查询分组

[英]ROR Associations group by query

I have the following 3 models and relationship between them: 我有以下3个模型及其之间的关系:

class Calendar < ActiveRecord::Base 
   has_many:fiscalcalendars
  has_many:voucherdatas ,:through => :fiscalcalendars
end

class Fiscalcalendar < ActiveRecord::Base
  belongs_to :calendar
  has_many :voucherdatas
end

class Voucherdata < ActiveRecord::Base
   has_many   :fiscalcalendars
  has_many   :calendars, :through => :fiscalcalendars
end
  • fields in calendar : id,monthname 日历中的字段:id,monthname
  • fields in fiscalcalendar :id, calendar_id,fiscalyearweek 财政日历中的字段:id,calendar_id,会计年度周
  • fields in voucherdata :id, vhour, fiscalyear week voucherdata中的字段:id,vhour,会计年度周

I want the sum of the vhour for each month 我想要每个月的vhour的总和

I can get it to group by fiscal week by doing 我可以通过以下方式将其按财务周分组

Voucherdata.sum(:vhour,:group=>:fiscalyearweek)

is there a simpler way to get it by month? 有没有更简单的方法可以按月获取?

This should do what you're asking for, assuming I understand your database relationship. 假设我了解您的数据库关系,这应该可以满足您的要求。

Voucherdata.sum(:vhour, :joins => :calendars, :group=> 'calendars.monthname)

However this statement won't work without a little modification. 但是,如果不作任何修改,该语句将不起作用。 You're not telling Rails how to link Voucherdata and Fiscalcalendar. 您没有告诉Rails如何链接Voucherdata和Fiscalcalendar。 With two :has_many relationships Rails doesn't know where to find the foreign key to link to the other one. 有两个:has_many关系,Rails不知道在哪里找到链接到另一个的外键。

You need to make a join model and either make it a :has_many, :through relationship or use a :has_and_belongs_to_many relationship. 您需要创建一个联接模型,并使其成为:has_many,:through关系,或者使用:has_and_belongs_to_many关系。 Once you've set that up the above statement will work without modification. 设置完之后,上面的语句无需修改即可工作。

Corrected model relationship and migration required. 更正了模型关系和所需的迁移。 Using a :has_and_belongs_to_many relationship (cleaner syntax): 使用:has_and_belongs_to_many关系(更简洁的语法):

class Calendar < ActiveRecord::Base 
  has_many:fiscalcalendars
  has_many:voucherdatas ,:through => :fiscalcalendars
end

class Fiscalcalendar < ActiveRecord::Base
  belongs_to :calendar
  has_and_belongs_to_many :voucherdatas
end

class Voucherdata < ActiveRecord::Base
  has_many   :calendars, :through => :fiscalcalendars
  has_and_belongs_to_many :fiscalcalendars
end

class CreateFiscalcalendarsVoucherdatasJoinTable ActiveRecord::Migration
  def self.up
    create_table :fiscalcalendars_voucherdatas :id => false do |t|
      t.integer :fiscalcalendar_id
      t.integer :voucherdata_id
    end
  end

  def self.down
     drop_table :fiscalcalendars_voucherdatas
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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