2012-01-08 2 views
1

다음 예제는 영화 모델에서만 서로 다릅니다.다형 다 대다

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

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

이 차이는 무엇을 의미합니까?


Example 1 :

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

class Movie < ActiveRecord::Base 
    has_many :taggings, :as => :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 

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

당신은 2 예 작동하는지 있습니까? 나는 창문에 레일 환경이 없다. 질문에 대한 이해를 돕기 위해

사례 1.

has_many :taggings, :as => :taggable 

여기서 "taggable"은 정확한 모델 이름이 아니며 단지 별칭입니다. (Taggable 클래스 없음)

case2.

has_many :taggings, :through => :taggable 

여기서 "taggable"은 실제 (exsting) 모델이어야하며, 어딘가에 Taggable 클래스가 있어야 함을 의미합니다. .. 예는 일 가정 http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

+0

감사합니다. 두 번째 사례가 작동하는지 잘 모르겠습니다. 블로그 게시물에서 이러한 코드 예제를 발견했습니다. 두 번째 게시물에는 ": through => : taggable"을 ": as => : taggable"로 변경하는 것에 대한 설명이 있습니다. Taggable 클래스가 없으면 제대로 작동하지 않을 수도 있습니다. –

1

및 taggable은 .. 주 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 
을 실제 모델이었다

은 참조