【问题标题】:has_many :through questionshas_many:通过问题
【发布时间】:2010-12-15 05:03:42
【问题描述】:

我以前使用 has_and_belongs_to_many,并已转换为 has_many :through。以下是它如何查找可以有许多用户玩的游戏列表。有了这个,我可以做 game.users 和 user.games....:

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

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

class GameUser < ActiveRecord::Base
  belongs_to :game
  belongs_to :user
end

还有我对连接表的数据库迁移:

create_table :game_users, :id => false do |t|
      t.column :game_id, :integer
      t.column :user_id, :integer
      t.column :player_index, :integer
    end

我不太确定我明白了这一切,请帮我检查一下我的事实:

  1. 依赖 => :destroy 是否正确?如果游戏或用户被破坏,我希望删除“game_users”连接表条目 - 但如果游戏被删除,我不希望用户被删除,反之亦然.....?

  2. uniq 字段应该说游戏只包含唯一用户,用户只包含唯一游戏。对吗?

  3. 数据库迁移和以前一样有:id => false。那仍然是正确的做法吗?我尝试在控制台中破坏游戏,并收到有关丢失 id 的投诉......所以我猜不是并试图理解原因。

我发现 Rails 的活动记录关联非常令人困惑。我想他们不应该是!

【问题讨论】:

  • 你对 :dependent => :destroy 的使用是正确的。

标签: ruby-on-rails activerecord has-many-through


【解决方案1】:

1:是的,没错

2:来自documentation on uniq

如果为真,将省略重复项 从收藏。有用的 与 :through 结合使用。

所以,是的,如果您的目标不是在 User 的 games-collection 中获得相同的游戏,也不是在 Game 的 users-collection 中获得相同的用户,那是正确的。都解释完了here

但是,它不会阻止创建重复的 GameUser。为此,您需要在 GameUser 模型中使用 validates_ uniqueness _of

class GameUser < ActiveRecord::Base
  validates_uniqueness_of :game_id, :scope => :user_id
end

3:不,你不想再使用 :id => false 了。通过从 has_and_belongs_to_many 切换到 has_many :through,您已将多对多连接表提升为完整模型 - GameUser - 它需要自己的 id。

this 虽然老了,但仍然是了解 has_many :through 的好文章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多