Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to build has_one association or update if it exists

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?

like image 591
lulalala Avatar asked Feb 01 '12 03:02

lulalala


2 Answers

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
like image 179
Bradley Priest Avatar answered Nov 15 '22 00:11

Bradley Priest


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.

like image 37
Woahdae Avatar answered Nov 15 '22 00:11

Woahdae