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
preguntado el 01 de febrero de 12 a las 03:02
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 es parecido a 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.