has_many :通过在连接表中创建重复项
我创建了 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.cities
具有 c
和 c.users
具有 u
而不复制连接表中的数据?
补充:
所以,如果我只选择 c.users << u
,我只能对城市
执行此操作吗?
cities = Array.new()
UserCity.where(:user_id => u.id).each do |uc|
cities << City.find(uc.city_id)
end
I created 3 models, User, City, UserCity.
User class:
class User < ActiveRecord::Base
has_many :user_cities, :dependent => :destroy, :uniq => true
has_many :cities, :through => :user_cities
end
City class:
class City < ActiveRecord::Base
has_many :user_cities, :dependent => :destroy, :uniq => true
has_many :users, :through => :user_cities
end
UserCity class:
class UserCity < ActiveRecord::Base
belongs_to :user
belongs_to :city
end
And then I tried
u = User.new()
c = City.new()
u.cities << c
c.users << u
p UserCity.all.size # => 2
user_cities table had duplicates. So then, I coded
UserCity class:
class UserCity < ActiveRecord::Base
validates :user_id, :uniqueness => {:scope => :city_id}
belongs_to :user
belongs_to :city
end
and run the same ruby code above. But it failed after c.users << u
because I prohibited duplicate.
How can I make u.cities
have c
and c.users
have u
without duplicating data in join table?
Added:
So, if I choose only c.users << u
, can I only do this for cities
?
cities = Array.new()
UserCity.where(:user_id => u.id).each do |uc|
cities << City.find(uc.city_id)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
选择
u.cities << c
或c.users <<你。它们中的每一个都会导致将一行插入到连接表中。
Choose either
u.cities << c
orc.users << u
. Each of them cause a row inserted in to the join table.您可能还想通过在数据库中添加索引来防止数据库中出现重复项,如果您不小心尝试添加重复的联接条目,这会引发错误。在迁移中做这样的事情:
You might also want to prevent duplicates in the db by adding an index in the db which would raise an error if you accidentally try to add a duplicate join entry. Do something like this in a migration: