My discount class has a sales_period. I want to write a method which can build this association when it does not exist, or updates it when it does exist. Currently I am writing the following if condition.
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
Is there a better way to do this, similar to find_or_create
?
Not quite what you're looking for but you can shorten it slightly.
def fetch_period
end_date = ...
period = sales_period || build_sales_period
period.end = end_date
end
find_or_initialize
is similar to first_or_initialize. Ex:
def fetch_period
end_date = ...
sales_period.find_or_initialize_by_end(end_date)
end
Also, I'd rename end
, it's a ruby keyword. You'll probably get some weird bug when something tries to eval
the code or some such, and it'll be super confusing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With