【问题标题】:How do I use the value of an attribute within a model? Ruby on Rails如何在模型中使用属性的值? Ruby on Rails
【发布时间】:2014-12-03 22:33:46
【问题描述】:

基本上,我有一个模型,Degree,它具有三个属性:degree_typeawarded_bydate_awarded

有两个值数组应该对awarded_by 有效。 degree_type 的两个有效值是"one""two"awarded_by 的有效值取决于"one""two"

如果degree_type"one"(具有"one" 的值,用户将输入),我希望awarded_by 的有效值是array_one。如果degree_type 的值为"two",我希望awarded_by 的有效值为array_two

这是目前为止的代码:

class Degree < ActiveRecord::Base
  extend School

  validates :degree_type, presence: true, 
    inclusion: { in: ["one",
                      "two"],
                 message: "is not a valid degree type"
               }

  validates :awarded_by, presence: true,
    inclusion: { in: Degree.schools(awarded_by_type) }
end

Degree.schools 根据度数类型输出一个数组,因此Degree.schools("one") 将返回array_one,其中

array_one = ['school01', 'school02'...]

我的问题是,我不知道如何在模型中访问degree_type 的值。

我在下面尝试的方法不起作用:

validates :awarded_by, presence: true,
    inclusion: { in: Degree.schools(:degree_type) }

我尝试使用before_type_cast,但要么使用不正确,要么出现其他问题,因为我也无法让它工作。

当我测试这个时,我得到:

An object with the method #include? or a proc, lambda or symbol is required, and must be supplied as the :in (or :within) option of the configuration hash

帮帮我? :) 如果需要更多信息,请告诉我。

编辑:此外,我仔细检查了这不是我的 Degree.schools 方法起作用 - 如果我进入 rails 控制台并尝试 Degree.schools("one")Degree.schools("two") 我确实得到了我应该得到的数组。 :)

再次编辑:当我尝试@Jordan 的回答时,在 awarded_by 不正确的情况下出现错误,因为在这些情况下,valid_awarded_by_valuesnil 并且没有用于 nil 对象的 include? 方法.因此我添加了一个 if 语句来检查 valid_awarded_by_values 是否为 nil(如果是 return),这就解决了问题!

我把它放在方法中,在 unless 语句之前和 valid_awarded_by_values 声明之后:

   if valid_awarded_by_values.nil?
      error_msg = "is not a valid awarded_by"
      errors.add(:awarded_by, error_msg)
      return
  end

【问题讨论】:

    标签: ruby-on-rails validation models


    【解决方案1】:

    最简单的方法是编写自定义验证方法as described in the Active Record Validations Rails Guide

    在你的情况下,它可能看起来像这样:

    class Degree < ActiveRecord::Base
      validate :validate_awarded_by_inclusion_dependent_on_degree_type
    
      # ...
    
      def validate_awarded_by_inclusion_dependent_on_degree_type
        valid_awarded_by_values = Degree.schools(degree_type)
    
        unless valid_awarded_by_values.include?(awarded_by)
          error_msg = "must be " << valid_awarded_by_values.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ')
          errors.add(:awarded_by, error_msg)
        end
      end
    end
    

    【讨论】:

    • 当我尝试使用它时,我的测试告诉我:NoMethodError: undefined method `include?'对于 nil:NilClass 我猜测放入 Degree.schools(degree_type) 的任何值都不是实际值,它应该是一个字符串 - 你知道如何访问它吗? (对不起,我在完成之前发布了这个,点击进入太快了)
    • 是的,问题是Degree.schools 正在返回nil。您可以使用 logger.debug 将任何值写入 Rails 日志。
    • 我想通了并编辑了我的问题 - 我只需要添加一个 if 语句来检查 Degree.schools 是否为零来解决问题。 :D 否则它似乎工作得很好,毕竟我不需要确切的值。 :) 非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    相关资源
    最近更新 更多