Unique with nested_form_for rails does not work

advertisements

I have models Vehicle, Tag, VehicleTag

class VehicleTag < ActiveRecord::Base
  attr_accessible :vehicle_id, :tag_id, :capacity

  belongs_to :vehicle
  belongs_to :tag

  validates_uniqueness_of :tag_id, :scope => [:vehicle_id]
end

and I have used 'nested_form_for' to enter value in vehicle_tags tables but validates_uniqueness_of is not working when user select same tags multiple times and its saving data in tables.

But when I have a single record in vehicle_tag with tag_id=2, vehicle_id=24 and when user select same tag again this time its thronging uniqueness validation. as I am getting first time we don't have value in DB and second time we have.

But I want to through uniqueness when user select multiple same tag.

EDIT: vehicle_tag table structure:

+-----+------------+--------+----------+---------------------+---------------------+
| id  | vehicle_id | tag_id | capacity | created_at          | updated_at          |
+-----+------------+--------+----------+---------------------+---------------------+
| 241 |          2 |      2 |        2 | 2014-04-22 11:35:11 | 2014-04-22 11:35:11 |
| 242 |          2 |      2 |        3 | 2014-04-22 11:35:11 | 2014-04-22 11:35:11 |
+-----+------------+--------+----------+---------------------+---------------------+

class Vehicle < ActiveRecord::Base
  has_many :vehicle_tags
  has_many :tags, :through => :vehicle_tags

  accepts_nested_attributes_for :vehicle_tags, :reject_if => proc { |a| a['capacity'].blank? }, allow_destroy: true
end

class Tag < ActiveRecord::Base
  has_many :vehicle_tags
  has_many :vehicles, :through => :vehicle_tags
end


you may try this, as in a seperate line

validates :tag_id, :uniqueness => true