【问题标题】:Rails 4 - method to check if all attributes are trueRails 4 - 检查所有属性是否为真的方法
【发布时间】:2016-06-05 04:04:08
【问题描述】:

我正在尝试在 rails 4 中制作应用程序。

我想在模型中编写一个方法来检查所有属性是否为真。

我正在尝试:

def ready_to_go
    if 
    [ payment == true, 
    && terms == true
    && identification == true
    && key_org == true
    && key_business == true
    && docs == true
    && funding == true
    && contract == true
    && governance == true
    && internal == true
    && preferences == true
    && address == true
    && interest == true ]
    end
  end

谁能看出这是怎么回事?

【问题讨论】:

  • define 错了,能不能简洁点?或者它不工作?我不明白为什么你有数组语法 [] 或者为什么它在 if 中没有任何内容。如果您只想返回 true 或 false,则删除 if 和数组语法
  • 而不是在模型self.attributes 中尝试这样来获取该模型的所有属性。

标签: ruby-on-rails methods


【解决方案1】:

试试Array.all?

[true, false].all? # false  
[true, true].all? # true

【讨论】:

    【解决方案2】:

    首先,使用? 符号将方法定义为谓词。然后删除与 true 的比较,只使用payment && terms && ...

    def ready_to_go?
      payment &&
      terms &&
      ...
    end
    

    【讨论】:

      【解决方案3】:

      [...] 是错误的。它定义了一个数组。具有一个元素“假”的数组被解释为真。只需删除括号(如果您确实需要它们以免混淆,请使用圆括号)。

      然后在同一行开始您的if。 如果您只想返回 true/false,则可以完全删除 if。 如果你的值是truefalsenil,你也不需要检查true:

      def ready_to_go
        payment &&
        terms &&
        identification &&
        ...
      end
      

      【讨论】:

        【解决方案4】:

        最简单的方法是定义方法并检查它是否准备好,然后:

        def ready_to_go
          [ payment, terms, identification, key_org, key_business, docs, funding, contract, governance, internal, preferences, address, interest].all?
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-06
          • 1970-01-01
          • 2015-08-08
          • 2013-03-19
          • 1970-01-01
          • 1970-01-01
          • 2011-03-28
          • 1970-01-01
          相关资源
          最近更新 更多