简体   繁体   中英

issue in has_and_belongs_to_many association in rails

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM