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

发布于 2024-12-05 05:42:05 字数 1335 浏览 0 评论 0原文

我创建了 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 具有 cc.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不再见 2024-12-12 05:42:05

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

Choose either u.cities << c or c.users << u. Each of them cause a row inserted in to the join table.

与酒说心事 2024-12-12 05:42:05

您可能还想通过在数据库中添加索引来防止数据库中出现重复项,如果您不小心尝试添加重复的联接条目,这会引发错误。在迁移中做这样的事情:

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

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:

add_index :cities_users, [:city_id, :user_id], unique: true
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文