Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Uniqueness validation for nested fields_for - Part2

I am new to coding - and have not enough reputation to comment this answer: Rails 3: Uniqueness validation for nested fields_for

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

I am a web designer but curious to learn coding, held with this from 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

above code with "ActiveModel::EachValidator" 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

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

"Subclasses must implement a validate(record) method. "


this is model file:

class Area < ActiveRecord::Base


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

  belongs_to :city

end

You can find complete code over here: https://github.com/syed-haroon/rose

like image 526
Syed Avatar asked Nov 04 '22 23:11

Syed


2 Answers

@Syed: I think you are trying to do this. else reply to my comment.

# 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
like image 82
Krishna Prasad Varma Avatar answered Nov 09 '22 14:11

Krishna Prasad Varma


I found the answer over here :

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

&

validates_uniqueness_of in destroyed nested model rails

This is for rails 2, one line need to me modified over here: add_to_base has been deprecated and is unavailable in 3.1. Use self.errors.add(:base, message)

like image 23
Syed Avatar answered Nov 09 '22 15:11

Syed