具有不同has_many关联的模型的计算方法

时间:2014-07-29 09:46:04

标签: ruby-on-rails-4 methods associations has-many

我写了一个为商业案例计算某个值的方法。

我的模特看起来像这样

class CEntry < ActiveRecord::Base
    belongs_to :bcase
end

class SEntry < ActiveRecord::Base
    belongs_to :bcase
end

class CnqEntry < ActiveRecord::Base
    belongs_to :bcase
end

class Bcase < ActiveRecord::Base
         has_many :c_entries, :dependent => :destroy
    has_many :s_entries, :dependent => :destroy
    has_many :cnq_entries, :dependent => :destroy

end

现在我为商业案例模型编写了这个方法

def int_rc
    x = 0
    self.c_entries.where(:hours != 0 && :order_no !=).each do |entry|
        x = x + (entry.hours * entry.rate.ratevalue)
    end
    return x.round(2)
end

但我需要这个用于c_entries,s_entries和cnq_entries,我想将它写3次是愚蠢的,因为它会是90%相同。

所以我尝试设置变量并用正确的对象类型填充它。多数民众赞成我拥有并且不起作用:

def int_rc(type)
    x = 0
    self.type.where(:hours != 0 && :order_no !=).each do |entry|
        x = x + (entry.hours * entry.rate.ratevalue)
    end
    return x.round(2)
end

然后我会打电话给@bcase.int_rc(c_entries)

您怎么看?

1 个答案:

答案 0 :(得分:1)

你很亲密;使用Ruby send method就是你所追求的。您可以使用send构建动态方法,向其传递符号或字符串。这里的最后三行是等价的;在irb中尝试:

a = "example"
a.chars # ['e', 'x', 'a', 'm', 'p', 'l', 'e']
a.send :chars
a.send "chars"

您还可以将参数传递给send

a = "example"
a.index('m') # 3
a.send :index, 'm' # equivalent to the above

因此,您的int_rc方法应该如下工作:

def int_rc(type)
    x = 0
    self.send(type).where(:hours != 0 && :order_no !=).each do |entry|
        x = x + (entry.hours * entry.rate.ratevalue)
    end
    return x.round(2)
end
相关问题