【问题标题】:Render different action for ajax vs html request in rails 3在 Rails 3 中为 ajax 与 html 请求呈现不同的操作
【发布时间】:2011-02-03 18:57:08
【问题描述】:

在 rails 3 中,我在照片控制器中的销毁操作有以下代码

 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 中是否有更清洁的方法。可能使用 respond_with 运算符?

谢谢

【问题讨论】:

    标签: ruby-on-rails ajax ruby-on-rails-3 redirect render


    【解决方案1】:

    这应该适合你:

    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

    以下是帖子中关于逻辑的引述:

    如果请求的是 :html 格式:

    • 如果是 GET 请求,调用渲染(这将显示视图 当前操作的模板)
    • 如果是 POST 请求并且资源存在验证错误,则呈现 :new (所以用户可以修复他们的 错误)
    • 如果是 PUT 请求并且资源存在验证错误,则呈现 :edit (所以用户可以修复他们的 错误)
    • 否则,重定向到资源位置(即 user_url)

    如果请求了其他格式,(即 :xml 或 :json)

    • 如果是 GET 请求,请在资源上调用 :to_format 方法并 发回去
    • 如果资源有验证错误,将错误发回 请求的格式与 :unprocessable_entity 状态码
    • 如果是 POST 请求,请在资源上调用 :to_format 方法并 用 :created 把它发回 状态和 :location 新的 创建资源
    • 否则,发回没有正文的 :ok 响应

    更多关于documentation 中的to_format 部分:

    首先我们尝试渲染一个模板,如果 模板不可用,我们 验证资源是否响应 :to_format 并显示出来。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      相关资源
      最近更新 更多