Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 Rails 3:模型之间的数学_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 3 Rails 3:模型之间的数学

Ruby on rails 3 Rails 3:模型之间的数学,ruby-on-rails-3,Ruby On Rails 3,假设我有以下结构: parts model: - title - weight - part_type_id part_type model: - quotation 我想为每个零件设定一个“价格”。这些模型使用关联(part:has\u one)和(part\u type:belling\u to)。这没关系 所以,基本上我要做的是创建一个虚拟属性,如下所示: class Parts < ActiveRecords::Base .. attr_accessor :price

假设我有以下结构:

parts model:
- title
- weight
- part_type_id

part_type model:
- quotation
我想为每个零件设定一个“价格”。这些模型使用关联(part:has\u one)和(part\u type:belling\u to)。这没关系

所以,基本上我要做的是创建一个虚拟属性,如下所示:

class Parts < ActiveRecords::Base
  ..
  attr_accessor :price

  def price
    quotation = PartType.find(self.part_type_id).quotation
    price = self.weight * quotation
  end
end
<% @parts.each do |part| %>
   <%= part.title %>
   <%= part.price %>
<% end %>
类部件
我可以这样称呼它:

class Parts < ActiveRecords::Base
  ..
  attr_accessor :price

  def price
    quotation = PartType.find(self.part_type_id).quotation
    price = self.weight * quotation
  end
end
<% @parts.each do |part| %>
   <%= part.title %>
   <%= part.price %>
<% end %>

这是做这件事的“正确”方法还是我应该怎么做?

你可能想用它来表示偏执:

attr_reader :price
单独改变价格没有多大意义,因此,既然他们真的想要得到你,那么最好用这个小小的改变来消除所有可能的bug。然后,您希望更改访问器以直接使用
attr\u reader
创建的实例变量:

def price
    return @price if(@price)
    @price = PartType.find(self.part_type_id).quotation * self.weight
end
假设
nil
false
都不是有效的价格,因此如果
if(@price)
失败,您不必担心反复计算
@price
;当实例变量在第一次访问时自动初始化为
nil
时,计算只应发生一次

在我看来,除了上面提到的小问题之外,我还觉得这很合理。

你可能想用它来表示偏执:

attr_reader :price
单独改变价格没有多大意义,因此,既然他们真的想要得到你,那么最好用这个小小的改变来消除所有可能的bug。然后,您希望更改访问器以直接使用
attr\u reader
创建的实例变量:

def price
    return @price if(@price)
    @price = PartType.find(self.part_type_id).quotation * self.weight
end
假设
nil
false
都不是有效的价格,因此如果
if(@price)
失败,您不必担心反复计算
@price
;当实例变量在第一次访问时自动初始化为
nil
时,计算只应发生一次


在我看来,除了上面提到的小问题之外,这是很合理的。

谢谢你的解释,首先我对使用
attr\u访问器
attr\u阅读器
感到困惑,但似乎如果它是一个只读属性,我真的应该选择
attr\u阅读器
。所以这样看起来没问题。谢谢你的解释,首先我对使用
attr\u访问器
attr\u阅读器
感到困惑,但似乎如果它是只读属性,我真的应该选择
attr\u阅读器
。这样看起来没问题。