Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 411
rails Avatar asked Jul 08 '11 06:07

rails


People also ask

What does Respond_to do in Rails?

respond_to takes the end of the call (e.g. blah. html, blah. json, etc) and matches the view specified. Other respond tos can be XML, CSV and many many more depending on the application.

What is Respond_to in Ruby?

respond_to is a Rails method for responding to particular request types.


2 Answers

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

like image 139
chrispanda Avatar answered Oct 06 '22 18:10

chrispanda


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

like image 33
Somesh Sharma Avatar answered Oct 06 '22 18:10

Somesh Sharma