[英]issue in has_and_belongs_to_many association in rails
currently exists user
with has_many project
当前存在具有 has_many
project
的user
but now i want to update project
has_many user
and user
has_many project
.但现在我想更新
project
has_many user
和user
has_many project
。
but i am getting error- Could not find table 'projects_users'但我收到错误- 找不到表'projects_users'
in project.rb在项目.rb
has_and_belongs_to_many :users
user.rb用户.rb
has_and_belongs_to_many :projects
Generated migration生成的迁移
rails g migration CreateProjectsUsersJoinTable
Getting error as-得到错误 -
Could not find table 'projects_users'找不到表“projects_users”
on index#controller line - @projects = current_user.projects在 index#controller 行 - @projects = current_user.projects
i think this might help run rails g migration create_project_users
in project_users table我认为这可能有助于在 project_users 表中运行
rails g migration create_project_users
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然后user.rb
has_many :project_users
has_many :projects, through :project_users
and in project.rb并在 project.rb
has_many :project_users
has_many :users, through :project_users
project_user.rb项目用户.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 版本大于 5,您可以使用 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在 project.rb 中
has_and_belongs_to_many :users
user.rb用户.rb
has_and_belongs_to_many :projects
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.