5

我是编码新手-并且没有足够的声誉来评论这个答案: 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”的代码会抛出这个错误:

“子类必须实现 validate(record) 方法。”


这是模型文件:

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

4

2 回答 2

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
于 2012-05-22T04:27:23.130 回答
1

我在这里找到了答案:

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

&

validates_uniqueness_of 在被破坏的嵌套模型导轨中

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

于 2012-06-08T02:29:49.690 回答