Best way to create a has_one association or update if one exists

My discount class has sales_period. I want to write a method that can build this association when it does not exist, or update it when it exists. I am currently 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, alike find_or_create?

+5
source share
2 answers

Not exactly what you are looking for, but you can cut it a bit.

def fetch_period
  end_date = ...
  period = sales_period || build_sales_period
  period.end = end_date
end
+10
source

find_or_initializesimilar to first_or_initialize . Example:

def fetch_period
  end_date = ...
  sales_period.find_or_initialize_by_end(end_date)
end

, end, ruby. , - , - eval , .

0

All Articles