【问题标题】:Ruby on Rails : is multiple respond_to block good in an action : best practiceRuby on Rails:在一个动作中是否有多个 respond_to 块好:最佳实践
【发布时间】:2015-08-26 08:56:35
【问题描述】:

我需要做条件检查是否渲染这个或那个。 用respond_to 块包装条件检查是否很好? 喜欢

   respond_to do |format|
     if @applicant.user_id.nil?
       # Some logic
       format.js
       format.html { redirect_to applicant_path(params[:id]) }
     else
       format.json { render json: {message: t('_applicants.flash.applicant_already_assigned')}, status: 400 }
     end
   end

我将在 if..else 内有多个 respond_to 块 喜欢

if @applicant.user_id.nil?
  # Some logic
  respond_to do |format|
    format.js
    format.html { redirect_to applicant_path(params[:id]) }
  end
else
  respond_to do |format|
    format.json { render json: {message: t('_applicants.flash.applicant_already_assigned')}, status: 400 }
  end
end

推荐的最佳方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby controller action response


    【解决方案1】:

    在我看来,控制器操作的代码很多。 Rails 在构建时考虑了DRY 方法,因此您可以尝试以下方法:

    如果你这样说:

    class SomeController < ApplicationController
      respond_to :html, :json , :js
    

    在你的控制器的开头,你可以让你的动作更苗条:

    def someaction
     if aplicant.id.nil?
      redirect_to applicant_path(params[:id])
     end
     else
        flash[:notice] = "Applicant already assigned" 
     end
    end 
    

    Read more about rails responses in this article.

    直接回答您的问题: 使用单个 respond_to 块的第一个选项更合理,因为它涉及编写更少的代码。正如我之前提到的,Rails 就是为了避免重复,而条件运算符中的两个响应块与编写 Rails 应用程序的风格背道而驰。

    【讨论】:

    • 此方法是否根据请求数据类型切换响应内容?
    • 很遗憾没有。如果您想使用不同的响应格式,您仍然必须使用 respond_to 块。我更新了我的答案,以便您更好地了解您的问题
    • 但我在某处读到,在 respond_to 块内编写逻辑并不好。我的第一种方法是不是违反了这个约定?
    • 我不知道你在哪里读到这个(如果你提供了一个很好的来源),但是从风格上看,第二种写作方法效率低下
    • 另外,不管条件是真还是假,你都将使用响应。所以在性能方面,我认为这也不重要。
    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2017-06-20
    • 2011-09-29
    • 1970-01-01
    • 2010-09-08
    相关资源
    最近更新 更多