简体   繁体   English

Ruby on rails:respond_to 和 respond_with 有什么区别?

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

What's the difference between respond_to and respond_with ? respond_torespond_with有什么区别? What do they do?他们在做什么? Can anyone post example with the screenshot of output?任何人都可以发布带有 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.本质上 respond_with 和 respond_to 做同样的事情,但是让你的代码更干净一些。 It is only available in rails 3 I think我认为它仅在 Rails 3 中可用

Both respond_to and respond_with does the same work, but respond_with tends to make code a bit simple, respond_torespond_with都做同样的工作,但是respond_with倾向于使代码有点简单,

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 ,使用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:您还需要提及 controller 中的格式:

respond_to :html,:json,:xml

When we pass @task to respond_with, it will actually check if the object is valid?当我们将@task传递给respond_with 时,它实际上会检查object 是否有效? first.第一的。 If the object is not valid, then it will call render:new when in a create or render:edit when in an update.如果 object 无效,那么它将在创建时调用 render:new 或在更新时调用 render:edit。

If the object is valid, it will automatically redirect to the show action for that object.如果 object 有效,它将自动重定向到该 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:您可以通过将:location选项添加到 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欲了解更多信息,请访问此博客

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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