gpt4 book ai didi

ruby-on-rails - 在 rails 3 中为 ajax 和 html 请求呈现不同的 Action

转载 作者:行者123 更新时间:2023-12-04 06:35:51 25 4
gpt4 key购买 nike

在 rails 3 中,我有以下代码用于我在照片 Controller 中的销毁操作

 def destroy
@photo = Photo.find(params[:id])
if @photo.destroy
flash[:notice] = t('photo.deleted')
respond_to do |format|
if request.xhr?
format.js
else
format.html {redirect_to photos_path}
end
end
else
flash[:alert] = t('.photo.error_deleting')
if request.xhr?
redirect_to(photos_url)
else
redirect_to(photo_path @photo)
end
end
end

目标本质上是重定向到索引页面(如果从标准链接调用),如果从远程链接调用则渲染 destroy.js。
这有效,但我想知道在 rails 3 中是否有更简洁的方法来执行此操作。可能使用 response_with 运算符?

谢谢

最佳答案

这应该适合你:

respond_to :html, :js

def destroy
@photo = Photo.find(params[:id])
if @photo.destroy
flash[:notice] = t('photo.deleted')
else
flash[:alert] = t('.photo.error_deleting')
end

respond_with(@photo)
end

这里有一篇很好的博客文章:
http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering

以下是有关逻辑的帖子的引用:

If the :html format was requested:

  • If it was a GET request, invoke render (which will display the view template for the current action)
  • If it was a POST request and the resource has validation errors, render :new (so the user can fix their errors)
  • If it was a PUT request and the resource has validation errors, render :edit (so the user can fix their errors)
  • Else, redirect to the resource location (i.e. user_url)

If another format was requested, (i.e. :xml or :json)

  • If it was a GET request, invoke the :to_format method on the resource and send that back
  • If the resource has validation errors, send back the errors in the requested format with the :unprocessable_entity status code
  • If it was a POST request, invoke the :to_format method on the resource and send that back with the :created status and the :location of the new created resource
  • Else, send back the :ok response with no body


更多关于 to_format部分来自 documentation :

First we try to render a template, if the template is not available, we verify if the resource responds to :to_format and display it.



还有一个关于它的 Railscast:
http://railscasts.com/episodes/224-controllers-in-rails-3

关于ruby-on-rails - 在 rails 3 中为 ajax 和 html 请求呈现不同的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4890428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com