0

所以我是 Rails n00b,我想创建一个“收藏夹”关系,以便用户可以拥有许多收藏的项目。我不完全确定如何做到这一点,这就是我要尝试的方式,但我不确定这是否是一个好习惯:

class User < ActiveRecord::Base
 has_many :favorites
 //other code
end

class Favorite < ActiveRecord::Base
 belong_to :user
 has_one :item
end

class Item < ActiveRecord::Base
 belongs_to :item
end

这是一个好方法吗?我应该使用has_and_belongs_to_many吗?我特别关注以下场景:假设用户有 100 个最喜欢的项目。当我执行 aUser.find(id)时,我还会检索 100 个收藏夹和 100 个项目吗?

如果它很重要:ruby 版本 1.9.3,rails 版本 3.2.11

4

3 回答 3

3

你能试试has_many => :through吗?

class User < ActiveRecord::Base
 has_many :favorites
 has_many :items, :through => :favorites
 //other code
end
于 2013-02-07T16:39:12.357 回答
2

在你的情况下 has_many :through 绝对是要走的路。我建议阅读: http: //guides.rubyonrails.org/association_basics.html

对您的问题特别感兴趣:

2.8 在 has_many :through 和 has_and_belongs_to_many 之间进行选择

Rails 提供了两种不同的方式来声明模型之间的多对多关系。更简单的方法是使用 has_and_belongs_to_many,它允许您直接进行关联:

class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end

声明多对多关系的第二种方法是使用 has_many :through。这通过连接模型间接地建立关联:

class Assembly < ActiveRecord::Base
  has_many :manifests
  has_many :parts, :through => :manifests
end

class Manifest < ActiveRecord::Base
  belongs_to :assembly
  belongs_to :part
end

class Part < ActiveRecord::Base
  has_many :manifests
  has_many :assemblies, :through => :manifests
end

最简单的经验法则是,如果您需要将关系模型作为独立实体使用,则应该设置一个 has_many :through 关系。如果您不需要对关系模型做任何事情,那么设置 has_and_belongs_to_many 关系可能会更简单(尽管您需要记住在数据库中创建连接表)。

如果您需要验证、回调或连接模型上的额外属性,您应该使用 has_many :through。

于 2013-02-07T17:18:30.907 回答
0

它比使用has_and_belongs_to_many.

当我执行 User.find(id) 时,我还会检索 100 个收藏夹和 100 个项目吗?

不,你只会得到用户对象。

更新:User.include(:favourites, :items).find(id)如果您想从用户对象多次调用项目表, 调用将使您加入表。

于 2013-02-07T17:09:07.307 回答