我的折扣類具有sales_period。我想寫一個方法,當它不存在時可以建立這種關聯,或者當它存在時更新它。目前我正在撰寫以下條件。建立has_one關聯或更新(如果存在)的更好方法
class Discount < ActiveRecord::Base
has_one :sales_period
def fetch_period
end_date = ...
if sales_period.nil?
build_sales_period(end: end_date)
else
sales_period.end = end_date
end
end
end
有沒有更好的方法來做到這一點,類似於find_or_create
?
謝謝,它稍微好一點,我認爲這是最好的。 – lulalala 2012-02-01 05:34:44
是的,這取決於fetch_period方法實際做了什麼,但如果你在多個地方使用它,我會考慮將那一行邏輯移動到它自己的方法 – 2012-02-01 08:05:21