我正在閱讀一篇文章並且遇到了第一個示例代碼。在模型中,實例變量被設置爲避免不必要的查詢。我還在其中一個欄目中看到了這一點(第二個例子)。另一方面,我讀了更多的文章,如果我使用這種模式,那麼我的應用程序可能不會線程安全,所以我不能利用我的彪馬網絡服務器。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。這樣我就明白了。 –