10

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?

13
  • What about save!? Is there already data in the table? Commented Sep 12, 2013 at 0:03
  • your obj and key have the same key values .. try obj = {"test1" => "test"} and it will work fine Commented Sep 12, 2013 at 0:03
  • What is the difference between "save" and "save!" ? Commented Sep 12, 2013 at 0:03
  • The bang method shows the stack trace in the console. Commented Sep 12, 2013 at 0:04
  • @Raghu Can you explain why that would be a problem? Commented Sep 12, 2013 at 0:05

1 Answer 1

20
  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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.