【发布时间】:2013-05-21 00:20:01
【问题描述】:
我正在关注“使用 Rails 进行敏捷 Web 开发”一书,并尝试将产品价格复制到 LineItem。覆盖 LineItem 上的设置器似乎是合适的选择。然而,正如在 Rails 中经常发生的那样,生成两个 setter 使练习变得不简单:
def product_id=(product_id)
product = Product.find(product_id)
write_attribute(:price, product.price)
write_attribute(:product_id, product_id)
end
def product=(product)
self.product_id = product.id #wtf? why isn't this the default?
end
无论我设置对象还是它的 id,此代码都按预期工作,在这两种情况下,价格都会被复制。是什么让我想知道:
为什么这个委托在不覆盖“product=(..)”的情况下不能工作?奇怪的是,如果不删除“self”,它将无法正常工作,显然它不会委托给“product_id=()”...
【问题讨论】:
-
通过将“product_id=”委托给“product=”而不是反之,对我的示例进行了明显的优化。这样,如果产品已经传递到 'product=' 中,则不必再次加载产品。
标签: ruby-on-rails rails-activerecord