LoginSignup
0
2

More than 1 year has passed since last update.

【備忘録】【Rails】多対多の関係のモデル実装(タグ編)

Posted at

自分用のメモです。
Railsで多対多の関係性を使って、タグ機能を実装する手順を残しておきます。

モデル

記事投稿の情報をもつTweetモデル、
タグの情報を持つTagモデル、
その2つを繋ぐ中間テーブルとしてTweet_Tag_Relationモデルを作成します。

1つのTweetは複数のTagを持ちえ、1つのTagは複数のTweetを持つ関係とします。

多対多を実装した経緯

TweetとTagが "複数 - 複数" 、つまり多対多の関係になっており、
中間テーブルというものを作りデータを管理する必要が出たため。

ER図

スクリーンショット 2021-06-16 16.23.35.png

下準備

tweetモデル作成

ターミナル
$ bundle exec rails g model tweet

マイグレーションファイルを編集

class CreateTweets < ActiveRecord::Migration[6.0]
  def change
    create_table :tweets do |t|
      t.string :name
      t.string :text
      t.timestamps
    end
  end
end

マイグレーションを実行

ターミナル
$ bundle exec rails db:migrate

tagモデル作成

ターミナル
$ bundle exec rails g model tag

マイグレーションファイルを編集

class CreateTags < ActiveRecord::Migration[6.0]
  def change
    create_table :tags do |t|
      t.string :name, null: false

      t.timestamps
    end
  end
end

マイグレーションを実行

ターミナル
$ bundle exec rails db:migrate

tweet_tag_relationモデル作成

ターミナル
$ bundle exec rails g model tweet_tag_relation tweet:references tag:references

マイグレーションを実行

ターミナル
$ bundle exec rails db:migrate

各モデルを編集

app/models/tweet.rb
class Tweet < ApplicationRecord
  has_many :tweet_tag_relations
  has_many :tags, through: :tweet_tag_relations
end
app/models/tag.rb
class Tag < ApplicationRecord
  has_many :tweet_tag_relations
  has_many :tweets, through: :tweet_tag_relations
end
app/models/tweet_tag_relation.rb
class TweetTagRelation < ApplicationRecord
  belongs_to :tweet
  belongs_to :tag
end

モデルの実装は以上。

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