Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord object not saving

I have this table that stores serialized objects:

class CachedObject < ActiveRecord::Base
  attr_accessible :key, :data
  validates_uniqueness_of :key
end

The data column stores a serialized object indexed by key. Pretty simple. I'm running this code to test:

key = "test"
obj = {"test" => "test"}
row = CachedObject.find_or_create_by_key key
row.data = obj.to_json
row.save

The object is getting created, but it's not saving back to the database. No error messages. What am I doing wrong here?

like image 634
kid_drew Avatar asked Sep 12 '13 00:09

kid_drew


1 Answers

  1. .save returns true or false. .save! raises errors. If you need to know why something is going wrong with a (somewhat) detailed message, use .save!.

  2. If key is not unique, the data will not be saved because the model will not pass validation. Try running Model.where(:key => 'test').destroy_all and reevaluate.

like image 148
OneChillDude Avatar answered Sep 27 '22 19:09

OneChillDude