LoginSignup
51
51

More than 5 years have passed since last update.

Rails アソシエーション 多対多の関係

Last updated at Posted at 2015-06-30

多対多モデル

今回例とする多対多モデルは
ArticleテーブルとTagテーブルです。
「記事(Article)は複数のタグも持つことが出来、
タグ(Tag)は複数の記事につけることが出来る」
という状態を考えます。

多対多モデルの定義

article.rb
class Article < ActiveModel::Base
  has_many :article_tags
  has_many :tags, through: :article_tags
end
tag.rb
class Tag < ActiveModel::Base
  has_many :article_tags
  has_many :tags, through: :article_tags
end
article_tag.rb
class ArticleTag < ActiveModel::Base
  belongs_to :article
  belongs_to :tag
end

throughによって「経由」を定義しています。

多対多モデルの使用

throughを使うことで下記のようなことが出来るようになります。

多対多関係を利用してレコードの作成

article = Article.create(title: "railsのマスター法")
article.tags.create(name: "rails")

これでタグを記事に関連付けて生成することが出来ます。

リレーションを追加する

article = Article.create(title: "railsのマスター法")
article.tags.create(name: "rails")

tag = Tag.create(name: "ruby")
article.tags << tag

リレーションを利用してレコードを取得する

article = Article.create(title: "railsのマスター法")
article.tags.create(name: "rails")

tag = Tag.create(name: "ruby")
article.tags << tag

article.tags #記事についたタグのレコードを取得出来る。
51
51
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
51
51