Add micropost/tag association

This commit is contained in:
Trevor Vallender 2023-10-19 18:35:48 +01:00
parent 3a6de86d48
commit b75f9277cc
5 changed files with 27 additions and 1 deletions

View File

@ -7,4 +7,7 @@ class Micropost < ApplicationRecord
validates :user,
:content,
presence: true
has_many :microposts_tags
has_many :tags, through: :microposts_tags
end

View File

@ -0,0 +1,6 @@
# frozen_string_literal: true
class MicropostsTag < ApplicationRecord
belongs_to :micropost
belongs_to :tag
end

View File

@ -2,4 +2,6 @@
class Tag < ApplicationRecord
validates :name, presence: true
has_many :microposts_tags
has_many :microposts, through: :microposts_tags
end

View File

@ -0,0 +1,8 @@
class CreateJoinTableTagsMicroposts < ActiveRecord::Migration[7.1]
def change
create_join_table :tags, :microposts, primary_key: [:tag_id, :micropost_id] do |t|
t.index [:tag_id, :micropost_id]
t.index [:micropost_id, :tag_id]
end
end
end

9
db/schema.rb generated
View File

@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.1].define(version: 2023_10_19_164620) do
ActiveRecord::Schema[7.1].define(version: 2023_10_19_172703) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
@ -70,6 +70,13 @@ ActiveRecord::Schema[7.1].define(version: 2023_10_19_164620) do
t.index ["user_id"], name: "index_microposts_on_user_id"
end
create_table "microposts_tags", id: false, force: :cascade do |t|
t.bigint "tag_id", null: false
t.bigint "micropost_id", null: false
t.index ["micropost_id", "tag_id"], name: "index_microposts_tags_on_micropost_id_and_tag_id"
t.index ["tag_id", "micropost_id"], name: "index_microposts_tags_on_tag_id_and_micropost_id"
end
create_table "tags", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false