Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register multiple before_save conditional callbacks on Rails 4

I have two different calculations to make on my model for two different fields. Before saving.

Class Event < ActiveRecord::Base
  #some relations
  before_save :method1, unless: :some_field_1?
  before_save :method2, unless: :some_field_2?

  def method1
    some_field_1 = some_other_field / 2
  end

  def method2
    some_field_2 = some_field_1 / 3
  end
end

The problem I'm having is that some_field_1 is null when method2 is called. My guess is that declaring the before_save callbacks like I'm doing is wrong.

  • Does the second before_save overrides the first?
  • Does the callbacks are executed in the same order in which they are declared?

I know I can wrap the two methods into one without the conditionals and problem solve, but I would prefer to have the conditional callbacks. And I want to know the correct way of doing it. The docs are not pretty clear about this.

Thanks a lot!

EDIT

For future reference. The code was Ok. The problem was somewhere else (the DB)!

like image 959
limoragni Avatar asked Dec 14 '22 15:12

limoragni


1 Answers

Does the second before_save overrides the first?

No

Does the callbacks are executed in the same order in which they are declared?

Yes

Since your attribute is not a boolean, you probably shouldn't use the question mark. Try:

before_save :method1, unless: :some_field_1
before_save :method2, unless: :some_field_2
like image 181
RPinel Avatar answered Apr 05 '23 23:04

RPinel