Rails 3:嵌套fields_for的唯一性验证 - 第2部分

时间:2012-05-19 18:27:48

标签: ruby-on-rails ruby

我是编码的新手 - 并且没有足够的声誉来评论这个答案: Rails 3: Uniqueness validation for nested fields_for

所以我创建这个问题为“第2部分”:)

嘿伙计们请帮助我 - 我是一名网页设计师,但很想学习编码,从我的日子开始就是这样。

# app/validators/nested_attributes_uniqueness_validator.rb   
class NestedAttributesUniquenessValidator < ActiveModel::EachValidator
        record.errors[attribute] << "Products names must be unique" unless value.map(&:name).uniq.size == value.size
      end
end

上面带有“ActiveModel :: EachValidator”的代码抛出此错误:

“区域1”的“未定义方法`map”:字符串“


# app/validators/nested_attributes_uniqueness_validator.rb   
class NestedAttributesUniquenessValidator < ActiveModel::Validator
    record.errors[attribute] << "Products names must be unique" unless value.map(&:name).uniq.size == value.size
  end
end

上面带有“ActiveModel :: Validator”的代码抛出此错误:

“子类必须实现验证(记录)方法。”


这是模型文件:

class Area < ActiveRecord::Base


  validates :name,
            :presence => true,
            :uniqueness => {:scope => :city_id},
            :nested_attributes_uniqueness => {:field => :name}

  belongs_to :city

end

您可以在此处找到完整的代码: https://github.com/syed-haroon/rose

2 个答案:

答案 0 :(得分:1)

@Syed:我想你是想这样做的。否则回复我的评论。

# app/models/city.rb
class City < ActiveRecord::Base
  has_many :areas
  validates :areas, :area_name_uniqueness => true
end

# app/models/area.rb
class Area < ActiveRecord::Base
  validates_presence_of :name
  validates_uniqueness_of :name  
end

# config/initializers/area_name_uniqueness_validator.rb
class AreaNameUniquenessValidator < ActiveModel::Validator
  def validate_each(record, attribute, value)
    record.errors[attribute] << "Area names must be unique" unless value.map(&:name).uniq.size == value.size
  end
end

答案 1 :(得分:1)

我在这里找到了答案:

https://rails.lighthouseapp.com/projects/8994/tickets/2160-nested_attributes-validates_uniqueness_of-fails

&安培;

validates_uniqueness_of in destroyed nested model rails

这是针对rails 2,我需要在这里修改一行: add_to_base已被弃用,在3.1中不可用。使用self.errors.add(:base, message)