0

Having resource Foobar with the following controller:

class FoobarController < ApplicationController
  def new
    @foobar = Foobar.new(baz: params[:baz])
    @foobar.build_data
  end

  def create
    @foobar = Foobar.new(foobar_params)
    respond_with(@foobar)
  end

  # ...
end

Is it necessary to set instance variable @foobar in #create method? Could not I just write

def create
  Foobar.new(foobar_params).tap &method(:respond_with)
end

?

1 Answer 1

2

It depends on what content types you respond with. The docs describe exactly what happens when you call respond_with. In your case, in the create action, respond_with is the same as the following, assuming you did not specify any other format than html in a respond_to call in your controller:

respond_to do |format|
  if @foobar.save
    flash[:notice] = 'Foobar was successfully created.'
    format.html { redirect_to(@foobar) }
  else
    format.html { render action: "new" }
  end
end

The only case where the @foobar instance variable would be necessary is, if there is a validation error and your new.html template includes @foobar. If the foobar_params are always valid, then respond_with will always respond with a redirect to the show action, so the instance variable is unnecessary.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.