Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Callback in Rails' model?

Just wondering if there is a way to do a conditional callback in Rails. I know you can do a conditional validation like so:

validates_uniqueness_of :email, :if => (1==1)

I often do things like this in my callbacks:

class LineItem < ActiveRecord::Base
  belongs_to :invoice
  belongs_to :line_item_group

  before_create :set_invoice_id
  def set_invoice_id
    unless self.invoice_id
      self.invoice_id = self.line_item_group.invoice_id
    end
  end
end

It would be great to clean that up a little.

like image 203
tybro0103 Avatar asked Jan 15 '12 21:01

tybro0103


1 Answers

class LineItem < ActiveRecord::Base
  before_create :set_invoice_id, unless: :invoice_id

  def set_invoice_id
    self.invoice_id = line_item_group.invoice_id
  end
end
like image 84
tokland Avatar answered Nov 15 '22 07:11

tokland