在你的情况下 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。