새로 만들기 + 저장 및 만들기의 레일 차이점
저는 rails를 처음 사용하고 new + save 메서드 사용과 create 메서드의 차이점을 이해하지 못합니다.
def create
@item = Item.new(params[:item])
respond_to do |format|
if @item.save
format.html { redirect_to @item, notice: 'Item was successfully created.' }
format.json { render json: @item, status: :created, location: @item }
else
format.html { render action: "new" }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
과:
def create
respond_to do |format|
if Item.create(params[:item])
format.html { redirect_to @item, notice: 'Item was successfully created.' }
format.json { render json: @item, status: :created, location: @item }
else
format.html { render action: "new" }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
내부적으로 create
호출 new
다음 save
어쨌든 :
def create(attributes = nil, options = {}, &block)
if attributes.is_a?(Array)
attributes.collect { |attr| create(attr, options, &block) }
else
object = new(attributes, options, &block)
object.save
object
end
end
이 것이 정확하지만 create
통화 new
및 다음 save
그 반환 값의 두 가지 대안 사이에 큰 차이가 있습니다.
Save
반환 중 하나 true
또는 false
객체가 데이터베이스 여부에 성공적으로 저장되었는지 여부에 따라 달라집니다. 그런 다음 위 질문의 첫 번째 예에 따라 흐름 제어에 사용할 수 있습니다.
Create
객체가 저장되었는지 여부에 관계없이 모델을 반환합니다. 이는 if
객체가 유효성 검사에 실패하고 저장되지 않은 경우에도 문의 맨 위 분기 가 항상 실행 된다는 점에서 위 코드 와 관련이 있습니다.
당신이 사용하는 경우 create
분기 논리를 당신은 당신이 사용하는 경우이 아니다있는 침묵 실패의 위험이있는 new
+를 save
.
create
경우 대안은 컨트롤러에 유용 할 수있는 respond_with
API (JSON / XML) 응답에 사용됩니다. 이 경우 객체에 오류가 unprocessable_entity
있으면 API에서 정확히 원하는 상태 인이라는 상태로 응답에 오류가 반환됩니다 .
특히 흐름 제어에 대한 반환 값에 의존하는 경우 항상 html에 new
+ save
옵션을 사용합니다 .
new
객체를 생성하지만 저장하지는 않습니다.
create
객체를 생성 하고 , 저장합니다 즉 .new
및.save
create!
개체를 생성하고 저장하려고하지만 검증이 실패 할 경우 예외가 발생 예 .new
와.save!
혼란스러운 항목 중 하나는 위의 작업이 개체에 대해 수행하는 작업이지만 특히 RESTful 환경에서 컨트롤러 메서드에도 유사한 이름이 지정된다는 것입니다. 예를 들어, 새 객체를 생성 한 다음 저장하는 create action ....과 객체 생성을 수행하는 또 다른 create action이 있습니다.
If you're wondering "why create an object if I'm not going to save it?" consider this - the system 'tries' to save the object - but a validation prevents it and the user is asked to fill in more information on a form, perhaps required fields. One wants the object to still be created (.new
) while this is going on and it will hold the values that have been assigned so far. However it doesn't actually get save
d until it passes the validations as well.
when you use, rails actually is creating the records but didn't save it, so in the process you can also assign smth
@item = Item.new(params[:item])
but when you use:
if Item.create(params[:item])
.....
it will immediately create and save
you can check it with rails c
참고URL : https://stackoverflow.com/questions/9791386/differences-in-rails-between-new-save-and-create
'program story' 카테고리의 다른 글
Facebook SDK 로그인은 iOS 9에서 내 애플리케이션을 다시 호출하지 않습니다. (0) | 2020.11.16 |
---|---|
표준 Python 클래스를 사용하여 이미지 크기를 얻는 방법 (외부 라이브러리를 사용하지 않고)? (0) | 2020.11.16 |
Mac 터미널 자동 완성 (0) | 2020.11.16 |
ID가 'com.google.gms.google-services'인 플러그인을 찾을 수 없습니다. (0) | 2020.11.16 |
프로덕션에 업로드하려고 할 때 Android 서명 APK가 서명되지 않은 APK로 표시됨 (0) | 2020.11.16 |