2014-06-24 2 views
0

그래서 레일스에서 ​​사용자 모델을 작성 중이며이 사용자 모델에는 연결된 전자 메일 주소 모델이 있습니다. 전자 메일 주소 모델에는 전자 메일의 고유성 제약 조건이 있습니다. 지금은 사용자가 accepts_nested_attributes_for : email_address하도록 설정했습니다. 이것은 생성에 큰 작동하지만 갱신에이 오류가 얻을 :고유성 제약 조건이있는 오류에 대해 nested_attributes_for를 업데이트하십시오.

u = User.create(:name => "foo", :new_password => "Passw0rd", 
     :email_address_attributes => {:email => "[email protected]"}) 
u.update({:name => "new name", 
     :email_address_attributes => {:email => "[email protected]"}}) 

가 어떻게이 이름 동안을 업데이트받을 수 있나요 : 나는 레일 콘솔에서이 작업을 수행하여이 버그를 다시 만들 수 있습니다

ActiveRecord::JDBCError: org.postgresql.util.PSQLException: 
ERROR: duplicate key value violates unique constraint 
"index_email_addresses_on_email" 

을 email_address에 신경 쓰지 마라. 어느 것이 변하지 않았습니까?

일부 다른 노트와 코드 :

내가 이메일에 내 EMAIL_ADDRESS 인덱스를하고는 제외하고 이메일 주소를 확인하지 않으려면 내가 레일 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 

답변

1

이 방법에 email_address_attributes를 업데이트 할 때, 당신은 실제로을 추가하는 귀하의 user에 대한 email_address 개체입니다.

u.update({:name => "new name", 
    :email_address_attributes => {:id => u.email_address.id, :email => "[email protected]"}}) 

또는 대안을, 다른 업데이트 문 컨트롤러에 관해서는

u.update({:name => "new name"}) 
u.email_address.update({:email => "[email protected]"}) 

에 사용자의 이메일 주소를 업데이트 할 수 있습니다, 모든 당신 : 당신은 즉, 속성으로 이메일 주소의 ID를 전달해야 전자 메일 주소의 :id 필드를 허용 된 매개 변수로 추가해야합니다.

def user_params 
    params.require(:user).permit(:name, email_address_attributes: [:id, :email]) 
end 

Strong Parameters Rails Guide의 강력한 매개 변수에 대한 자세한 정보가 있습니다. 자신의 것과 비슷한 설정을 확인하려면 More Example section을 확인하십시오.

+0

이것은 효과가 있습니다. 중요한 것은 : id를 email_address_attributes에 추가하는 것이 었습니다. 나는 가지고 있었다 : 전자 우편 그러나 아닙니다 : id. 감사. – NateSHolland

+0

문제가 없습니다! 내가 도울 수있어서 기뻐! –

1

을 사용하고 있습니다 생성에, 당신은 검증에 그것을 추가 할 수 있습니다

validates :email_address, presence: true, on: :create

1

사용 "update_only" "accepts_nested_attributes_for"이 같은에서 옵션 : 이미 대신 새로운 하나를 만드는,있는 경우

accepts_nested_attributes_for :email_address, :update_only => true 

이 방법은 활성 레코드가 자식 레코드를 업데이트합니다. 이는 고유 제한 조건을 처리해야합니다.

관련 문제