2014-11-02 4 views
1

난 레일 애플 리케이션을 쓰고 있는데 왜 잘못된 매개 변수를 update_attributes에 전달하면 true를 반환하는지 알아 내려고하고있다.@ user.update_attributes (nil)가 true를 반환하는 이유는 무엇입니까?

유효한 params도 true를 반환합니다. 예를 들어

:

@user.update_attributes(params[:user]) 
=> true 

@user.update_attributes(params[:whatever]) 
=> true 

또한

@user.update_attributes(false) 
=> true 

@user.update_attributes(nil) 
=> true 

모두가 true를 돌려

. 왜? 그리고 update_attributes에 유효한 매개 변수가 있는지 어떻게 확인합니까?

답변

1

update_attributes은 전달 된 속성을 업데이트하고 아무 속성도 전달되지 않으면 업데이트 할 것이없고 레코드가 성공적으로 저장 될 수 있습니다.

update_attributes은 유효성 검사로 인해 레코드를 저장할 수없는 경우 false를 반환합니다. 그러나 해시의 속성이 잘못되었다는 것을 의미하지는 않습니다. 레코드를 유효하지 않게 만든 필드가 다른 곳에서 설정된 필드 일 수 있습니다. 당신이 무엇을 통과있어하는 유효한 경우에 따라서 update_attributes에 관계없이 true를 돌려줍니다 알 수없는 특성을

@user.update_attributes(vegetable: "carrot") 
#> ActiveRecord::UnknownAttributeError: unknown attribute: vegetable 
1

#update_attributes는 먼저 모델 인스턴스가 #valid인지 확인합니다. 계속해서 데이터베이스에 쓰십시오. 모델 인스턴스가 #valid?가 아닌 경우 false를 반환합니다. 모델 인스턴스의 문제점을 확인하려면 모델의 #errors를 살펴보십시오.

first_name을 비워 둘 수없는 확인이있는 경우 그런 다음 false를 반환합니다 :

@user.update_attributes(first_name: nil) 
=> false 

@user.errors.first 
=> [:first_name, "can't be blank"] 

을 2665

def update_attributes(attributes) 
    self.attributes = attributes 
    save 
    end 

true 또는 falsesave 메서드에서 반환되는 깊은 이해 소스 코드 # 파일 액티브/lib 디렉토리/active_record/base.rb, 라인 . 따라서 잘못된 개체가있을 경우 false이됩니다. 그리고 대량 할당 예외의 경우 ActiveModel::MassAssignmentSecurity::Error.

Unknown Attributes은 대량 할당 예외로 간주됩니다.

+0

를 업데이트하려고하면

# record has validation that email address must be valid format @user.email = "invalid address" @user.update_attributes(name: "Fred") => false # due to email error # record has validation that email address must be valid format @user.email = "[email protected]" @user.update_attributes(name: "Fred") => true 

update_attributes은 당신이 뭔가를하려고하지 않는 한, 예외를 발생합니다 그 모델에 유효하지 않습니까? – Arel