Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set attributes in an ActiveRecord Object before I save it?

I am trying to understand the Active Record Callbacks, but they do not work, like I want to.

e.g.

Model

Checklist<ActiveRecord...
attr_accessible :item1, :item2, :done # they are all boolean

before_save :check_done

private
def check_done
  if item1 && item2
   write_attribute :done, true
  else
   write_attribute :done, false
  end
end

this doesn't work if I instantiate an object in the console and try to save it, the save operation returns "false" :(

What's wrong with this code? thanks in advance :)

EDIT: It looks like there is something wrong with the "before_save" call, if I use "after_save", the code works...but the attribute isn't saved (obviously). That's really strange

EDIT 2 Wierd...the development logs shows this

FROM sqlite_master
 WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
  [1m[35mChecklist Load (0.2ms)[0m  SELECT "checklists".* FROM "checklists" ORDER BY checklists.id DESC LIMIT 1
WARNING: Can't mass-assign protected attributes: id

but that is really odd, because if I remove the attr_accessible line I do still get this error...

EDIT 3 If anyone asks, yes I am trying to update an existing record.

EDIT 4 Yes, I like to edit If I type in the console

c.save => # false
c.errors => #<OrderedHash {}>
like image 738
tabaluga Avatar asked Sep 16 '10 09:09

tabaluga


2 Answers

The problem with your callback is that it returns false if either item1 or item2 is false.

From the Active Record Callbacks documentation:

If the returning value of a before_validation callback can be evaluated to false, the process will be aborted and Base#save will return false.

The solution is simple; return true at the end of your callback, like so:

def check_done
  self.done = (item1 && item2)
  return true
end
like image 121
Pär Wieslander Avatar answered Oct 13 '22 12:10

Pär Wieslander


before_save { |record|
  record.done = item1 && item2
}
like image 32
buru Avatar answered Oct 13 '22 12:10

buru