【发布时间】:2013-03-28 19:18:36
【问题描述】:
我的架构有Articles 和Journals,可以用Tags 标记。这需要一个与我的Tagging 连接表具有多态关系的has_many through: 关联。
好的,这是简单且有据可查的部分。
我的问题是Articles 可以同时拥有主标签和子标签。主要标签是我最感兴趣的,但我的模型还需要跟踪这些子标签。子标签只是描述Article 的标签,它们不太重要,但来自Tags 的同一个全局池。 (事实上,一个Article 的主标签可能是另一个的子标签)。
实现这一点需要Article 模型与Tagging 模型有两个关联,以及与Tags 有两个has_many through: 关联(即#tags 和#sub-tags)
这是我目前所拥有的,虽然有效但不会将主标签和子标签分开。
class Article < ActiveRecord::Base
has_many :taggings, as: :taggable
has_many :tags, through: :taggings
has_many :sub_taggings, as: :taggable, class_name: 'Tagging',
source_type: 'article_sub'
has_many :sub_tags, through: :sub_taggings, class_name: 'Tag', source: :tag
end
class Tagging < ActiveRecord::Base
# id :integer
# taggable_id :integer
# taggable_type :string(255)
# tag_id :integer
belongs_to :tag
belongs_to :taggable, :polymorphic => true
end
class Tag < ActiveRecord::Base
has_many :taggings
end
我知道在某处我需要找到source 和source_type 的正确组合,但我无法解决。
为了完整起见,这里是我用来测试这个的 article_spec.rb — 目前在“不正确的标签”上失败了。
describe "referencing tags" do
before do
@article.tags << Tag.find_or_create_by_name("test")
@article.tags << Tag.find_or_create_by_name("abd")
@article.sub_tags << Tag.find_or_create_by_name("test2")
@article.sub_tags << Tag.find_or_create_by_name("abd")
end
describe "the correct tags" do
its(:tags) { should include Tag.find_by_name("test") }
its(:tags) { should include Tag.find_by_name("abd") }
its(:sub_tags) { should include Tag.find_by_name("abd") }
its(:sub_tags) { should include Tag.find_by_name("test2") }
end
describe "the incorrect tags" do
its(:tags) { should_not include Tag.find_by_name("test2") }
its(:sub_tags) { should_not include Tag.find_by_name("test") }
end
end
在此先感谢您提供的任何帮助。主要问题是我不知道如何告诉 Rails 用于 Articles 中 sub_tags 关联的 source_type。
【问题讨论】:
标签: ruby-on-rails activerecord has-many-through polymorphic-associations tagging