다음 예제는 북 및 영화 모델에서만 서로 다릅니다.다형 다 대다
예 1 : Book has_many :taggings, :as => :taggable
예 2 : Book has_many :taggings, :through => :taggable
이 차이는 무엇을 의미합니까?
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
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
감사합니다. 두 번째 사례가 작동하는지 잘 모르겠습니다. 블로그 게시물에서 이러한 코드 예제를 발견했습니다. 두 번째 게시물에는 ": through => : taggable"을 ": as => : taggable"로 변경하는 것에 대한 설명이 있습니다. Taggable 클래스가 없으면 제대로 작동하지 않을 수도 있습니다. –