Oğuzhan Göller
Oğuzhan Göller

Reputation: 15

How to set up multiple belongs_to and has_many relations in Rails::ActiveRecord?

I am trying to create a movies app where a movie can have multiple categories and a category can have multiple movies. I want to access categories of a movie like this:

aMovie.categories

I expect this query to return ActiveRecord_Associations_CollectionProxy

and the reverse also applies

aCategory.movies

Below are my models and migrations

class Movie < ApplicationRecord
  validates :name, presence: true
end
class Category < ApplicationRecord
  validates :name, presence: true
end
class CreateMovies < ActiveRecord::Migration[5.2]
  def change
    create_table :movies do |t|
      t.string :name
      t.text :description
      t.integer :year
      t.float :rating

      t.timestamps
    end
  end
end
  def change
    create_table :categories do |t|
      t.string :name

      t.timestamps
    end
  end
end

How should i adjust my migrations and models?

Thanks in advance

Upvotes: 0

Views: 36

Answers (1)

Kamal Pandey
Kamal Pandey

Reputation: 1596

You should create intermediate join table

Movie_categories
belongs_to :movie
belongs_to :category

Movie
has_many :movie_categories
has_many :categories, through: :movie_categories

Category
has_many :movie_categories
has_many :movies, through: :movie_categories

You can refer to has_many through relationship in https://guides.rubyonrails.org/association_basics.html

Upvotes: 1

Related Questions