私のスキーマはTags
とタグ付けできるArticles
とJournals
です。これにはhas_many through:
と、Tagging
のジョインテーブルとの多相関係が関連付けられている必要があります。2つの多形を持つRailsモデルhas_many through:オブジェクトタグ付けのための関連
これは簡単で文書化された部分です。
私の問題は、Articles
がプライマリタグとサブタグの両方を持つことができるということです。プライマリタグは私が最も関心を持っているものですが、私のモデルもこれらのサブタグを追跡する必要があります。サブタグは、あまり重要ではないが、Tags
の同じグローバルプールに由来するArticle
を記述する単なるラベルです。 (実際には、Article
のプライマリタグは別のサブタグかもしれません)。これを達成
は、これは私が有効ではないながら、これまで持っているものであるTagging
モデルには2つの団体やTags
に2つのhas_many through:
協会(すなわち#tags &#サブタグ)
を持っているArticle
モデルが必要プライマリタグとサブタブを分離しないでください。
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にsource_typeを記事のsub_tags関連付けに使用するように指示する方法を考えることができないということです。