rails
rails

Reputation: 161

Ruby on rails: What's the difference between respond_to and respond_with?

What's the difference between respond_to and respond_with ? What do they do? Can anyone post example with the screenshot of output?

Thanks.

Upvotes: 15

Views: 9804

Answers (2)

Somesh Sharma
Somesh Sharma

Reputation: 569

Both respond_to and respond_with does the same work, but respond_with tends to make code a bit simple,

Here in this example,

def create
  @task = Task.new(task_params)

  respond_to do |format|
   if @task.save
    format.html { redirect_to @task, notice: 'Task was successfully created.' }
    format.json { render :show, status: :created, location: @task }
   else
    format.html { render :new }
    format.json { render json: @task.errors, status: :unprocessable_entity }
   end
 end
end

The same code using respond_with ,

def create
  @task = Task.new(task_params)
  flash[:notice] = "Task was successfully created." if @task.save
  respond_with(@task)
end

also you need to mention the formats in your controller as:

respond_to :html,:json,:xml

When we pass @taskto respond_with, it will actually check if the object is valid? first. If the object is not valid, then it will call render :new when in a create or render :edit when in an update.

If the object is valid, it will automatically redirect to the show action for that object.

Maybe you would rather redirect to the index after successful creation. You can override the redirect by adding the :location option to respond_with:

def create
  @task = Task.new(task_params)
  flash[:notice] = @task.save ? "Your task was created." : "Task failed to save." 
  respond_with @task, location: task_path
end

For more information visit this Blog

Upvotes: 2

chrispanda
chrispanda

Reputation: 3234

There is a pretty complete answer here. Essentially respond_with does the same thing as respond_to but makes your code a bit cleaner. It is only available in rails 3 I think

Upvotes: 13

Related Questions