如何使用模式创建重复行

时间:2013-02-14 06:59:02

标签: ruby-on-rails-3 indexing schema duplicates

在Rail中,我有这个模式(用于汽车和用户habtm之间的连接表)

  create_table "cars_users", :id => false, :force => true do |t|
    t.integer "user_id"
    t.integer "car_id"
  end

  add_index "cars_users", ["car_id", "user_id"], :name => "index_cars_users_on_car_id_and_user_id"
  add_index "cars_users", ["user_id", "car_id"], :name => "index_cars_users_on_user_id_and_car_id"

但由于某些错误,我在此表中有重复的行。

不应该index处理那个吗?

1 个答案:

答案 0 :(得分:1)

尝试:

add_index :cars_users, [ :user_id, :car_id ], :unique => true, :name => 'by_user_and_car'

它会引发异常,但您可以添加自己的验证

class User < ActiveRecord::Base
  has_and_belongs_to_many :cars, :before_add => :validates_car
  def validates_car(car)
    errors.add(:car, "already created" ) if self.cars.include? car
  end
end