2012-08-29 94 views
0

在我的Rails 3.2.8应用程序中,我试图计算所有的用户产品和税额。它应该得到产品的总和,然后是每个产品的税。如何获得父协会的总和?

class Product 
    attr_accessible :amount, :location_id, :tax_id 
    belongs_to :tax 
    belongs_to :location 
    belongs_to :user 
    belongs_to :tax, :class_name => "Tax" 

    def self.total 
    self.sum(:amount) + self.tax.sum(:amount) 
    end 
end 

Tax.rb

class Tax < ActiveRecord::Base 
    attr_accessible :amount, :date, :location_id 
    belongs_to :user 
    belongs_to :location 
    has_many :products 
end 

所以,当我尝试这样一个范围:

<%= number_to_currency(current_user.products.total) %> 

这当然给我一个错误:

undefined method `tax' for #<Class:0x57f5298> 

H我可以写这个让它工作吗?

谢谢。

+4

您正在混合类和实例属性/方法 – apneadiving

+0

为什么您将税作为相关对象?为什么不把税作为产品的属性? – Andrew

+1

您可以发布相关的税务类来源吗? –

回答

3

tax不是类产品

尝试以下方法(弱性能)产品的实例方法:

​​
+0

奇怪。我不得不升级到rails 3.2.8,然后开始工作。谢谢。 – LearningRoR

1

我不是伟大的的ActiveRecord的新的查询方法。我的客人我有点老式,倾向于更倾向于SQL,但这应该“有效”地得到你想要的东西。

def self.total 
    self.select('sum(products.amount + taxes.amount) AS sum').joins(:tax).try(:sum, 0) 
    end 
+0

这实际上使它回到空白。另外,为什么有产品,而不只是'金额+ tax.amount'?即使我尝试过,这对我也不起作用。 – LearningRoR

1

从该行

<%= number_to_currency(current_user.products.total) %> 

我了解,当前用户需要从他的产品和税收的总和。 您之前所做的与当前用户无关,而是与产品的整个表格相关,当然本表中的某些产品可能与当前用户无关。

所以这就是我认为它可能是如何。

#Instance method for current user 
class User < ... 
    def product_tax_total 
    products.joins(:tax).select('SUM(products.amount + taxes.amount) AS sum').sum 
    end 
end 

而且使用这样的:

<%= number_to_currency(current_user.product_tax_total) %> 

更新:

您可以使用范围链查询:

class Product 
    scope :today, lambda { where(:date => Date.today) } 
end 

然后IT连锁

class User < ... 
    def product_tax_total 
    products.today.joins(:tax).select('SUM(products.amount + taxes.amount) AS sum').sum 
    end 
end 
+0

不知道为什么这不起作用。它给了我一个参数错误。也可能很难使用它,因为我有其他方法,如def self。今天 其中(:date => Date.today) end'。我也有产品的日期栏。这就是为什么我试图将它放在Product类中的原因。 – LearningRoR

+0

在github上分享您的代码,以了解真正发生了什么。 – megas

+0

我希望这可以帮助:https://gist.github.com/3589646 – LearningRoR