ruby on rails - update nested_attributes_for errors with uniqueness constraint -
so i'm working on build user model in rails , user model have associated email address model. email address model has uniqueness constraint on email. right have set user accepts_nested_attributes_for :email_address. works great on create on update error:
activerecord::jdbcerror: org.postgresql.util.psqlexception: error: duplicate key value violates unique constraint "index_email_addresses_on_email"
i can recreate bug doing in rails console:
u = user.create(:name => "foo", :new_password => "passw0rd", :email_address_attributes => {:email => "foo@bar.com"}) u.update({:name => "new name", :email_address_attributes => {:email => "foo@bar.com"}})
how update name while not caring email_address. hasn't changed?
some other notes , code:
i index email_address on email , i'm using rails 4.
class user < activerecord::base belongs_to :email_address validates :email_address, :presence => true accepts_nested_attributes_for :email_address end class emailaddress < activerecord::base validates_format_of :email, :with => rfc822::emailaddress validates :email, :presence => true has_one :user end
when update email_address_attributes
in way, you're adding new email_address
object user
. need pass email address's id attribute, i.e.:
u.update({:name => "new name", :email_address_attributes => {:id => u.email_address.id, :email => "foo@bar.com"}})
or alternatively, can update user's email address in different update statement
u.update({:name => "new name"}) u.email_address.update({:email => "foo@bar.com"})
as controller, need add together email addresses's :id
field permitted parameter.
def user_params params.require(:user).permit(:name, email_address_attributes: [:id, :email]) end
there more info strong parameters in strong parameters rails guide. check out more illustration section setup similar yours.
ruby-on-rails ruby ruby-on-rails-4
No comments:
Post a Comment