2012-01-08 39 views
1

書籍およびムービーのモデルのみが次のように異なります。多形多対多

例1:Book has_many :taggings, :as => :taggable

例2:Book has_many :taggings, :through => :taggable

この違いは何を意味するのでしょうか?


Example 1

​​

Example 2:

class Book < ActiveRecord::Base 
    has_many :taggings, :through => :taggable 
    has_many :tags, :through => :taggings 
end 

class Movie < ActiveRecord::Base 
    has_many :taggings, :through => :taggable 
    has_many :tags, :through => :taggings 
end 

class Tag < ActiveRecord::Base 
    has_many :taggings 
    has_many :books, :through => :taggings, :source => :taggable, :source_type => "Book" 
    has_many :movies, :through => :taggings, :source => :taggable, :source_type => "Movie" 
end 


class Tagging < ActiveRecord::Base 
    belongs_to :taggable, :polymorphic => true 
    belongs_to :tag 
end 

答えて

1

あなたは第二の例では、動作しますか?私は窓の中にレール環境を持っていません。 ご質問についてご理解いただけるように、

case1

has_many :taggings, :as => :taggable 

ここで、「taggable」は正確なモデル名ではなく、単なるエイリアスです。 (Taggableクラスはありません)

case2ここ

has_many :taggings, :through => :taggable 

「タグ付けできるが、」本当の(exsting)モデルでなければならない、私はどこかにタグ付けできるクラスが存在しなければならないわけ。 ...例が働いていたと仮定すると、http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

+0

ありがとうございます。私はまた、2番目のケースがうまくいくかどうかはわかりません。私はこれらのコード例をブログ記事で見つけました。第2の記事では、 ":through =>:taggable"を ":as =>:taggable"に変更するというコメントがあります。おそらく、Taggableクラスがないとうまくいかないでしょう。 –

1

とタグ付けできるが... Siweiは、おそらく示唆するように、実際には動作しません...

:as defines a polymorphic association 

:through says that 
    if A has many B's 
    and B has many C's 
    then A has many C's through B 
を実際のモデルだった:

を参照してください。