0

'userは、多くのpostsあり、productは多くのpostsを持っており、任意のpostはどちらかuserproductではなく、両方に属することができます。1つのモデルと2つのhas_many関係をRailsに格納する最も簡単な方法は?

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

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

私が必要なものを表現します:

私はposts_relationshipsテーブルに格納されていると書かれたようhas_many :through関係を考えます。 これは正しい方法ですか?それは複雑な関係ではないので、私はできるだけ簡単に書きたいと思っています。

答えて

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 
+0

これは私の必要としているようです。私はちょうど[this](http://stackoverflow.com/questions/697840/polymorphic-associations-in-rails)の質問に対するスクリーンキャストを見ましたが、かなり古いです。多形関連に関するRails 3固有のチュートリアルを見ていきます。 – pthesis

+1

スクリーンキャストはインプリメンテーションと大きく異なるわけではありませんが、オブジェクトコンテキストでそれらについて考えるのは難しいかもしれません。実際にはそれは外的な主要な関係です。実装がそれほど変わっていないことに気付き始めたら、それを考え始めましょう。ここには[Polymorphic Association Docs](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations)があります。 – Azolo

+0

リンクのおかげでアゾロ! – pthesis

関連する問題