【问题标题】:issue in has_and_belongs_to_many association in railsrails 中 has_and_belongs_to_many 关联的问题
【发布时间】:2020-08-06 06:27:15
【问题描述】:

当前存在 user 和 has_many project

但现在我想更新 project has_many useruser has_many project

但我收到错误 - 找不到表 'projects_users'

在项目.rb中

has_and_belongs_to_many :users

用户.rb

has_and_belongs_to_many :projects

生成的迁移

rails g migration CreateProjectsUsersJoinTable

得到错误-

找不到表“projects_users”
在 index#controller 行 - @projects = current_user.projects

【问题讨论】:

  • 出于好奇,你rake db:migrate了吗?如果是这样,您的CreateProjectUsersJoinTable 迁移是什么样的?另外,rails g migration CreateProjectUsersJoinTable 应该是 rails g migration CreateProjectsUsersJoinTable(项目复数形式)。
  • @jvillian rake db:migrate 已被执行,我参考了stackoverflow.com/questions/5120703/…

标签: ruby-on-rails


【解决方案1】:

我认为这可能会有所帮助 运行rails g migration create_project_users 在 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

然后是user.rb

has_many :project_users
has_many :projects, through :project_users

在 project.rb 中

has_many :project_users
has_many :users, through :project_users

project_user.rb

belongs_to :user
belongs_to :project

【讨论】:

    【解决方案2】:

    如果您的 rails 版本大于 5,您可以使用 create_join_table 进行新的迁移。

    rails g migration CreateJoinTableProjectsUsers project user
    

    这将生成以下内容:

    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
    

    并且 在project.rb中

    has_and_belongs_to_many :users
    

    用户.rb

    has_and_belongs_to_many :projects
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多