簡體   English   中英

Ruby on rails:respond_to 和 respond_with 有什么區別?

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

respond_torespond_with有什么區別? 他們在做什么? 任何人都可以發布帶有 output 屏幕截圖的示例嗎?

謝謝。

這里有一個相當完整的答案。 本質上 respond_with 和 respond_to 做同樣的事情,但是讓你的代碼更干凈一些。 我認為它僅在 Rails 3 中可用

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

您還需要提及 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM