【问题标题】:Ruby on rails: What's the difference between respond_to and respond_with?Ruby on rails:respond_to 和 respond_with 有什么区别?
【发布时间】:2018-03-16 17:18:39
【问题描述】:

respond_torespond_with 有什么区别? 他们在做什么? 任何人都可以发布带有输出屏幕截图的示例吗?

谢谢。

【问题讨论】:

  • 不是respond_to 而不是respond_do 吗?还是我错过了什么?

标签: ruby-on-rails


【解决方案1】:

有一个相当完整的答案here。本质上 respond_with 和 respond_to 做同样的事情,但是让你的代码更干净一些。我认为它仅在 rails 3 中可用

【讨论】:

【解决方案2】:

respond_torespond_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

您还需要将控制器中的格式描述为:

respond_to :html,:json,:xml

当我们将@task传递给respond_with时,它实际上会检查对象是否有效?第一的。如果对象无效,那么它会在创建时调用 render :new 或在更新时调用 render :edit。

如果对象有效,它将自动重定向到该对象的显示操作。

也许你宁愿在成功创建后重定向到索引。您可以通过将 :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

欲了解更多信息,请访问Blog

【讨论】:

    猜你喜欢
    • 2010-11-17
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2011-07-29
    • 2011-10-19
    相关资源
    最近更新 更多