![](/img/trans.png)
[英]What's the difference between respond_to and respond_with in Rails?
[英]Ruby on rails: What's the difference between respond_to and respond_with?
respond_to
和respond_with
有什么区别? 他们在做什么? 任何人都可以发布带有 output 屏幕截图的示例吗?
谢谢。
这里有一个相当完整的答案。 本质上 respond_with 和 respond_to 做同样的事情,但是让你的代码更干净一些。 我认为它仅在 Rails 3 中可用
respond_to和respond_with都做同样的工作,但是respond_with倾向于使代码有点简单,
在这个例子中,
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
使用respond_with的相同代码,
def create
@task = Task.new(task_params)
flash[:notice] = "Task was successfully created." if @task.save
respond_with(@task)
end
您还需要提及 controller 中的格式:
respond_to :html,:json,:xml
当我们将@task
传递给respond_with 时,它实际上会检查object 是否有效? 第一的。 如果 object 无效,那么它将在创建时调用 render:new 或在更新时调用 render:edit。
如果 object 有效,它将自动重定向到该 object 的显示操作。
可能您更愿意在创建成功后重定向到索引。 您可以通过将: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
欲了解更多信息,请访问此博客
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.