program story

새로 만들기 + 저장 및 만들기의 레일 차이점

inputbox 2020. 11. 16. 08:15
반응형

새로 만들기 + 저장 및 만들기의 레일 차이점


저는 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_withAPI (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 saved 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

반응형