Invalid ActiveRecord Rails Object

I have this table in which serialized objects are stored:

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

The data column stores the serialized object indexed by the key. Pretty simple. I run this code for testing:

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

The object is created, but does not save it back to the database. No error messages. What am I doing wrong here?

+4
source share
1 answer
  • .save returns true or false . .save! causes errors. If you need to know why something is going wrong with a (somewhat) verbose message, use .save! .

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

+9
source

Source: https://habr.com/ru/post/1501750/


All Articles