以下示例仅在图书和电影模型中有所不同。
示例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
答案 0 :(得分:1)
你确定第二个例子有效吗?我在Windows中没有rails环境。 为了解我的问题,
情形1。
has_many :taggings, :as => :taggable
这里“taggable”不是一个确切的Model名称,它只是一个别名。 (没有Taggable类)
情况2。
has_many :taggings, :through => :taggable
这里“taggable”必须是一个真实的(exsting)模型,我的意思是某处必须有一个Taggable类。
参考:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
答案 1 :(得分: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