0

We've got this object, @current_employer, that's acting a bit weird. Update fails the first time, succeeds the second.

(byebug) @current_employer.update(settings_params)
false
(byebug) @current_employer.update(settings_params)
true

Here's where we initialise it:

  @current_employer = Employer.find(decoded_auth_token[:employer_id])

It's just a standard "find".

Current workaround:

if @current_employer.update(settings_params) || @current_employer.update(settings_params)

...

Anyone seen this before?

Update

Tracked it down to this line in a "before_save" call

  # self.is_test = false if is_test.nil?

Seems like is_test is a reserved keyword?

Will Taylor
  • 1,994
  • 2
  • 23
  • 36

2 Answers2

0

Solved

The full callback, with the fix commented inline:

def set_default_values
  self.has_accepted_terms = false if has_accepted_terms.nil?
  self.live = true if live.nil?
  self.account_name.downcase!
  self.display_name ||= account_name
  self.display_name ||= ""
  self.contact_first_name ||= ""
  self.contact_last_name ||= ""
  self.phone_number ||= ""
  self.is_test_account = false if is_test_account.nil?
  true # FIX. The proceeding line was returning 'false', which was giving us a 'false' return value for the before_save callback, preventing the save.
end
Will Taylor
  • 1,994
  • 2
  • 23
  • 36
0

Model

If it's failing in one instance and succeeding almost immediately afterwards, the typical issue is that you're passing incorrect / conflicting attributes to the model.

I would speculate that the settings_params you're sending have a value which is preventing the save from occurring. You alluded to this with your update:

# self.is_test = false if is_test.nil?

The way to fix this is to cut out any of the potentially erroneous attributes from your params hash:

def settings_params
   params.require(:employer).permit(:totally, :safe, :attributes)
end 

Your model should update consistently - regardless of what conditions are present. If it's failing, it means there'll be another problem within the model save flow.

--

Without seeing extra information, I'm unable to see what they may be


Update

A better way to set default values is as follows:

How can I set default values in ActiveRecord?

You may wish to use the attribute-defaults gem:

class Foo < ActiveRecord::Base
  attr_default :age, 18
  attr_default :last_seen do
    Time.now
  end
end
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147