tybro0103 tybro0103 - 4 months ago 8
Ruby Question

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.

Answer

Is this it?

before_create :set_invoice_id, :unless => :invoice_id

def set_invoice_id
  self.invoice_id = line_item_group.invoice_id
end

By the way, is item.invoice_id always equal to item.line_item_group.invoice_id? if so, I don't think that's very orthodox in SQL.

Comments