在Rails中与一个模型存储两个has_many关系的最简单方法是什么?

时间:2012-03-17 00:53:26

标签: ruby-on-rails-3 associations has-many-through model-associations

'user有很多postsproduct有很多posts,任何给定的post都可以属于user或一个product但不是两个。

我认为has_many :through关系存储在posts_relationships表中,并且写成:

Class User < ActiveRecord::Base
has_many :posts, :through => posts_relationships

Class Product < ActiveRecord::Base
has_many :posts, :through => posts_relationships

会表达我的需要。 这是最正确和最简单的方法吗?这不是一个复杂的关系,所以我想尽可能简单地写出来。

1 个答案:

答案 0 :(得分:2)

考虑多态关联。

Class User < ActiveRecord::Base
  has_many :posts, :as=>:postings
end

Class Product < ActiveRecord::Base
  has_many :posts, :as=>:postings
end

class Post
  belongs_to :posting, :polymorphic=> :true
end