has_many:通过在连接表中创建重复项

时间:2011-09-17 12:34:11

标签: ruby-on-rails duplicates ruby-on-rails-3.1 has-many-through

我创建了3个模型,User,City,UserCity。

用户类:

class User < ActiveRecord::Base
  has_many :user_cities, :dependent => :destroy, :uniq => true
  has_many :cities, :through => :user_cities
end

城市课程:

class City < ActiveRecord::Base
  has_many :user_cities, :dependent => :destroy, :uniq => true
  has_many :users, :through => :user_cities
end

UserCity类:

class UserCity < ActiveRecord::Base
  belongs_to :user
  belongs_to :city
end

然后我尝试了

u = User.new()
c = City.new()
u.cities << c
c.users << u
p UserCity.all.size # => 2

user_cities表有重复项。那么,我编码了

UserCity类:

class UserCity < ActiveRecord::Base
  validates :user_id, :uniqueness => {:scope => :city_id}
  belongs_to :user
  belongs_to :city
end

并运行上面相同的ruby代码。但它在c.users << u之后失败了,因为我禁止重复。

如何让u.citiescc.users拥有u而无需在联接表格中复制数据?


添加了:

因此,如果我只选择c.users << u,我只能为cities执行此操作吗?

cities = Array.new()
UserCity.where(:user_id => u.id).each do |uc|
  cities << City.find(uc.city_id)
end

2 个答案:

答案 0 :(得分:2)

选择u.cities << cc.users << u。它们中的每一个都会导致在连接表中插入一行。

答案 1 :(得分:0)

您可能还希望通过在db中添加索引来防止数据库中出现重复,如果您不小心尝试添加重复的连接项,则会引发错误。在迁移中执行类似的操作:

add_index :cities_users, [:city_id, :user_id], unique: true