0

currently exists user with has_many project

but now i want to update project has_many user and user has_many project.

but i am getting error- Could not find table 'projects_users'

in project.rb

has_and_belongs_to_many :users

user.rb

has_and_belongs_to_many :projects

Generated migration

rails g migration CreateProjectsUsersJoinTable

Getting error as-

Could not find table 'projects_users'
on index#controller line - @projects = current_user.projects

rock
  • 348
  • 4
  • 18
  • Out or curiosity, did you `rake db:migrate`? If so, what does your `CreateProjectUsersJoinTable` migration look like? Also, should `rails g migration CreateProjectUsersJoinTable` be `rails g migration CreateProjectsUsersJoinTable` (Projects pluralized). – jvillian Aug 06 '20 at 06:59
  • @jvillian ```rake db:migrate``` has been executed i took reference from https://stackoverflow.com/questions/5120703/creating-a-many-to-many-relationship-in-rails – rock Aug 06 '20 at 07:01

2 Answers2

3

i think this might help run rails g migration create_project_users in project_users table

class CreateProjectUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :project_users do |t|
      t.integer :user_id
      t.integer :project_id
    end
  end
end

then user.rb

has_many :project_users
has_many :projects, through :project_users

and in project.rb

has_many :project_users
has_many :users, through :project_users

project_user.rb

belongs_to :user
belongs_to :project
Brian Ngeywo
  • 398
  • 1
  • 5
  • 10
1

If your rails version is greater than 5, you can make a new migration using create_join_table.

rails g migration CreateJoinTableProjectsUsers project user

This will generate following:

class CreateJoinTableProjectsUsers < ActiveRecord::Migration
  def change
    create_join_table :projects, :users do |t|
      t.index [:project_id, :user_id]
      # t.index [:user_id, :project_id]
    end
  end
end

And in project.rb

has_and_belongs_to_many :users

user.rb

has_and_belongs_to_many :projects
NeK
  • 846
  • 5
  • 13