0

在 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处理吗?

4

1 回答 1

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
于 2013-02-14T07:11:01.403 回答