Assigning value to serialized attribute causes SerializationTypeMismatch
I find it surprising that this has not been asked yet, so I am hoping I am doing something fundamentally wrong and help will arrive开发者_如何学Python soon. I have this
create_table "foo", :force => true do |t|
t.text "bar", :null => false
...
end
class Foo < AR::Base
serialize :bar, Bar
end
class Bar
def initialize(hsh)
@data = hsh # and some more code...
end
end
Now once I add
class Foo < AR::Base
before_validation :get_bar, :on => :create
def get_bar
self.bar = Bar.new({})
end
end
I am not able to create any Foo objects because the assignment to Bar raises SerializationTypeMismatch. I have debugged this and found out that the value of bar is by default an empty string and AR validates that and fails.
The question is how to get rid of it.
When you create your migration you need to set a default.
create_table "foo", :force => true do |t|
t.text "bar", :null => false, :default => Bar.new({}).to_yaml
...
end
精彩评论