Rails 3: Uniqueness Check for Nested_Fields - Part2

I'm new to coding - and I don't have enough reputation to comment on this answer: Rails 3: checking for uniqueness for nested_fields

So, I am creating this question as "Part 2" :)

Help me guys help me - I'm a web designer, but I'm curious to know how to do this with my days.

# 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

the above code with "ActiveModel :: EveryValidator" will throw this error:

"undefined method` map 'for" Area 1 ": String"


# 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

the above code with "ActiveModel :: Validator" will throw this error:

"Subclasses must implement a validation (write) method."


This is the model file:

class Area < ActiveRecord::Base


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

  belongs_to :city

end

Here you can find the full code: https://github.com/syed-haroon/rose

+5
2

@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

All Articles