update_attribute not doing anything after first_or_create if record does not exist previously

133 views Asked by At

I do a first_or_create statement, followed by a update_attributes:

hangout = Hangout.where(tour: tour, guide: current_user).first_or_create
hangout.update_attributes(priority: current_user.priority)

If the record already existed, it updates the priority. If it doesn't exist previously, there is no update. Why?

Thanks!

2

There are 2 answers

0
Vasfed On

update_attributes (aka update) returns a boolean indicating if there was an error, if you do not check it - use bang-version update! so that exception will not be ignored.

Most probably record does not get created due to validation. Also when you're updating new record just after create - better use first_or_create(priority: current_user.priority) or first_or_initialize(with subsequent update) to spare extra DB write.

0
zawhtut On
  def update_attributes!(attributes)
    self.attributes = attributes
    save!
  end

update attribute with bang call the save with bang.

def save!(*args, &block)
  create_or_update(*args, &block) || raise(RecordNotSaved.new("Failed to save the record", self))
end

Inside the save! RecordNotSave error will be raise if it cannot save the record.

so you can customize the error handing from your code.

begin
    hangout.update_attributes!(priority: current_user.priority)
rescue RecordNotSaved => e
    #do the exception handling here
end