方法给出ActiveRecord :: Relation错误?

我有3个名为Price,UnitPrice和Purchase的模型。 Price和UnitPrice模型有一个名为amount的属性,我试图将其范围扩大并获得两者的总和。 我创建了两个范围,一个用于两个模型的总和。 另一个范围是获取两个模型的date字段的date属性。

我正在尝试这样做:

 <%= number_to_currency(current_user.purchases.today.total) 

但得到错误:

 NoMethodError in pages#home undefined method `today' for # 

我的代码:

 class Purchase  Date.today) && self.unit_price.where(:date=> Date.today) end end class Price < ActiveRecord::Base attr_accessible :amount, :date belongs_to :user has_many :purchases end class UnitPrice < ActiveRecord::Base attr_accessible :amount, :date belongs_to :user has_many :purchases end 

我该怎么办?

方法totaltoday在模型对象上定义。 当你调用current_user.purchases你关联到一个has_many关系,这意味着它最终是数组。 因此,您无法在其上调用Purchase方法。 你可以这样做:

  class Purchase < ActiveRecord::Base # ... scope :today, lambda { joins(:unit_price, :price). where(:price => {:date => Date.today}, :unit_price => { :date => Date.today }) } def total self.price.sum(:amount) + self.unit_price.sum(:amount) end end 

然后像这样调用它:

  <%= number_to_currency(current_user.purchases.today.inject{ |sum, p| sum + p.total }) %> 

可以在关系上调用范围。

你需要调用注入,因为total是Purchase方法,关系是Array,所以你需要聚合数组。 为了保持代码清洁,您可能希望在User上定义today_purchases_total方法,然后您可以将其称为:

  <%= number_to_currency(current_user.today_purchases_total) %> 

有关这方面的更多信息,您可以参考http://guides.rubyonrails.org/active_record_querying.html#scopes和所有RoR指南。

我认为您的问题可能是您使用的是类方法而不是实例方法。 在您的Purchase类中,删除self. 在方法定义之前:

 class Purchase < ActiveRecord::Base def total self.price.sum(:amount) + self.unit_price.sum(:amount) end def today self.price.where(:date => Date.today) && self.unit_price.where(:date=> Date.today) end end