0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Railsの多対多の関係でのレコード追加について

Posted at

何をしたか

Railsで多対多の関係もモデルがあった時に、レコード追加をどうできるのかが気になったため試しました。

今回の例

今回は下記のモデルを使用します。
image.png

movie.rb
class Movie < ApplicationRecord
  has_many :movie_tags
  has_many :tags, through: :movie_tags
  accepts_nested_attributes_for :tags
end
tag.rb
class Tag < ApplicationRecord
  has_many :movie_tags
  has_many :movies, through: :movie_tags
  accepts_nested_attributes_for :movies
end
movie_tag.rb
class MovieTag < ApplicationRecord
  belongs_to :movie
  belongs_to :tag
end

レコード追加をしてみる

まずは既存のtagに紐づくmovieのレコードを追加したいと思います。

Tag.find_by(name: 'ジブリ').movies.create(title: 'もののけ姫')

Tag.find_by(name: 'ジブリ').movies.pluck(:title)
# => ['もののけ姫']

問題なくできました。

次はtagとそれに紐づくmovieを同時にレコードを追加してみます。

Tag.create(name: 'ピクサー', movies_attributes: [{title: 'カーズ'}, {title: 'トイ・ストーリー'}])

Tag.find_by(name: 'ピクサー').movies.pluck(:title)
# => ["カーズ", "トイ・ストーリー"]

こちらも問題なくできました。

もちろん逆にmovieとそれに紐づくtagを同時にレコードを追加する場合もできました。

Movie.create(title: '君の名は。', tags_attributes: [{name: '青春'}, {name: '新海'}])

Movie.find_by(title: '君の名は。').tags.pluck(:name)
# => ["青春", "新海"]

中間テーブルがあるのに、中間テーブルを意識せずにレコードを追加できるのでとても使いやすいなと思いました。

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?