【问题标题】:rails custom validation for array returning undefined method errorrails自定义验证数组返回未定义的方法错误
【发布时间】:2014-04-10 19:55:21
【问题描述】:

我正在为名为 Project 的模型中的属性编写自定义验证方法。这是我的代码:

def self.skill_options
  categories = Craft.all.collect{|craft| craft.label} #should change this later
  return categories
end

validate :validate_tag_list

def validate_tag_list
  puts skill_options.inspect.to_s
  puts 'validate tag list is happening'
  self.tag_list.each do |tag|
    if self.skill_options.include?(tag)
      puts tag.to_s + 'is included yo'
    else
          puts tag.to_s + 'not included yo'
          self.errors.add(:tag_list, "#{tag} is not a valid skill.")
    end
  end
end

由于某种原因,有人告诉我:

NameError (undefined local variable or method `skill_options' for #<Project:0x007fb6fc02ac28>)

我不确定这是为什么。我在同一模型中对名为 category 的不同属性进行了另一个验证。此验证非常有效。代码如下:

def self.category_options
  categories = Craft.all.collect{|craft| craft.label} #should change this later
end
validates :category,  inclusion: {in: category_options}

唯一的区别是第一次验证(关于技能)需要自定义验证,因为它是一个数组。

如何消除错误?

【问题讨论】:

    标签: ruby-on-rails ruby validation model-view-controller ruby-on-rails-4


    【解决方案1】:

    您将skill_options 定义为Project 类方法,因此您应该这样调用它:

    Project.skill_options
    

    因为在实例方法中,self(因此是隐式接收器)是Project 实例而不是类。并且Project 实例没有定义skill_options 方法。

    【讨论】:

      【解决方案2】:

      Ruby 有一些你可以做的非常强大的内省。您可以只使用self.class 来获取当前对象的类,因为skill_options 被定义为类级别的方法。此外,还有一些代码清理。抱歉,忍不住:

      def self.skill_options
        Craft.pluck(:label)
      end
      
      validate :validate_tag_list
      
      def validate_tag_list
        tag_list.each do |tag|
          unless self.class.skill_options.include?(tag)
            errors.add(:tag_list, "#{tag} is not a valid skill.")
          end
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多