我正在阅读一篇文章并且遇到了第一个示例代码。在模型中,实例变量被设置为避免不必要的查询。我还在其中一个栏目中看到了这一点(第二个例子)。另一方面,我读了更多的文章,如果我使用这种模式,那么我的应用程序可能不会线程安全,所以我不能利用我的彪马网络服务器。rails何时设置实例变量|| =
可以告诉我何时何地我应该使用这种模式?
1日例如:
def first_order_date
if first_order
first_order.created_at.to_date
else
NullDate.new 'orders'
end
end
private
def first_order
@first_order ||= orders.ascend_by_created_at.first
end
第二个示例
def shipping_price
if total_weight == 0
0.00
elsif total_weight <= 3
8.00
elsif total_weight <= 5
10.00
else
12.00
end
end
def total_weight
@total_weight ||= line_items.to_a.sum(&:weight)
end
修订问题
1例
当我看到这个 'first_order_date' 总是在对象上调用(https://robots.thoughtbot.com/rails-refactoring-example-introduce-null-object ),所以我不完全明白额外的查询是如何实现的应避免。我敢肯定,我错了,但据我所知,这可能只是
def first_order_date
if orders.ascend_by_created_at.first
first_order.created_at.to_date
else
NullDate.new 'orders'
end
end
还是可以使用@first_order
别的地方呢?
第二个示例
在原来问题的代码不等于这个?
def shipping_price
total_weight = line_items.to_a.sum(&:weight)
if total_weight == 0
0.00
elsif total_weight <= 3
8.00
elsif total_weight <= 5
10.00
else
12.00
end
end
我在这里看到他们与定义total_weight
实现,但为什么它更好地在我的例子中使用实例变量?
joshua,您是否也可以回答这些问题:1.为什么在shipping_price方法的第一行中定义'total_weight = line_items.to_a.sum(&:weight)'不够?正如我所看到的,它只会运行一次查询。 2.你在哪里使用轨道应用程序中的“memoization”? –
我更新了我的答案。 –
谢谢joshua。这样我就明白了。 –