レールActiveRecord関係なく、所属団体
-
19-09-2019 - |
質問
私が3モデル:
- 記事:されています
- タグ:を含むタグ
- ArticleTag:うに関連づけるための多対一のタグ第関係です。が含まれますtag_id、article_id.
の問題なんであんなの活動記録技術とはわかりません適切な方法を定義します。現在、私が間違っているのは、はたしてい
ArticleTag
belongs_to :article
belongs_to :tag
今の私の考えたのはその追加
Article
:has_many :tag
なんなのかすればすぐに対応してくれるので近づくことが正しくです。のは助かります!
解決
かんなが参加モデルです。結合モデルで開催していまショートカットキーに対する協会とその他のモデルです。例えば、もしかしたい録音時のタイムスタンプのタッチ.その情報が記録されに対する参加モデルです。
行わない場合は、参加モデルは、それを使用できる簡単な has_and_belongs_to_many
協会:
class Article < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :articles
end
と Tagging
参加モデルである名以上 ArticleTag
でのようになります:
class Article < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :article
belongs_to :tag
end
他のヒント
関係は一方通行であるとき、
あなたはhas_many
を使用する必要があります。記事には、多くのタグを持っていますが、タグも多くの記事を持っているので、それは非常に適切ではありません。より良い選択はhas_and_belongs_to_many
される可能性があります:記事には多くのタグを持っており、それらのタグにも記事を参照します。 A belongs_to B
は、参照のBことを意味します。 A has_one B
はBが参照することを意味します。
ここであなたが見るかもしれない関係の要約は次のとおりです。
Article
has_and_belongs_to_many :tags # An article has many tags, and those tags are on
# many articles.
has_one :author # An article has one author.
has_many :images # Images only belong to one article.
belongs_to :blog # This article belongs to one blog. (We don't know
# just from looking at this if a blog also has
# one article or many.)
私の頭の上から、条は次のようになります。
has_many :article_tags
has_many :tags, :through => :article_tags
所属していません StackOverflow