보통 if @user.save
은 ActiveRecord를 사용하여 개체가 데이터베이스에 성공적으로 저장되었는지 확인합니다. 거기에서 플래시 메시지를 설정하고 어딘가에 리디렉션 할 수 있습니다. else
절에서 @user.errors
을 검사하여 무엇이 잘못되었는지 파악하고 처리 할 수 있습니다. 이 6 장에 설명 된대로 마이클 하틀에 따르면
def create
#Set user object attributes using strong parameters
@user = User.new(user_params)
#Attempt to save @user
if @user.save
flash[:notice] = 'User saved successfully'
redirect_to somewhere_else_url
else
#Saving failed, we can inspect @user.errors for more information
flash[:alert] = 'User was not saved.'
#If using a form library @user.errors will be displayed graphically when rendering the :new action
render :new
end
end
하지만 @ user.save가 저장 작업을 수행하고있는 것처럼 보입니다. 데이터베이스에 모델을 저장 한 다음 true를 반환합니다. –
수정. '@ user.save'는 객체를 저장하고 에러없이 저장하는 경우에만 true를 반환하고, 에러가 발생하면 false를 반환합니다. 이를 통해 데이터베이스 저장의 성공 여부에 따라 논리를 작성할 수 있습니다. http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-save – danielrsmith
필자는 인수가 true 또는 false를 저장하는 변수 인 if 문에만 익숙하다고 생각합니다. –