简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM