What's the difference between respond_to
and respond_with
?
What do they do?
Can anyone post example with the screenshot of output?
Thanks.
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.
respond_to is a Rails method for responding to particular request types.
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
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 @task
to 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With