Let’s assume I have two models.
class User < ActiveRecord::Base
has_one :blog
end
class Blog < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
validates_uniqueness_of :user_id
end
Let’s assume I have one user with a blog. For some reason, let’s pretend I call create_blog for the same user (I know it should not be an option since the user already has a blog). If this blog doesn’t pass the validations, and it won’t, not only isn’t saved, but it deletes the previous blog the user has.
Why is this happening? Why the initial blog gets deleted? Is this behavior expected or is there something I missing?
By calling
create_blogyou’re telling Rails to discard the previous blog. There isn’t a way around this (that I am aware of) that doesn’t involve doing something like this: