has_many 在关联用户和项目时出现关联错误

问题描述 投票:0回答:2

我使用了 has_many :通过关联两个模型(即用户和项目)之间的多对多关系,但似乎存在一些错误,因为在多对一关系中运行良好的查询会抛出错误。有人可以检查一下吗!架构文件如下:

    ActiveRecord::Schema.define(version: 2018_12_19_170114) do

  create_table "project_users", force: :cascade do |t|
    t.integer "user_id"
    t.integer "project_id"
    t.index ["project_id"], name: "index_project_users_on_project_id"
    t.index ["user_id"], name: "index_project_users_on_user_id"
  end

  create_table "projects", force: :cascade do |t|
    t.text "content"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "picture"
    t.string "title"
    t.index ["user_id"], name: "index_projects_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.integer "enroll"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "password_digest"
    t.boolean "admin", default: false
    t.index ["email"], name: "index_users_on_email", unique: true
  end

end

user.rb 文件包含代码:

类用户< ApplicationRecord has_many :project_users has_many :projects, through: :project_users def feed projects end end

The project.rb file has the code:

    class Project < ApplicationRecord
      has_many :project_users
      has_many :users, :through => :project_users

project_user.rb 文件有代码:

class ProjectUser < ApplicationRecord
    belongs_to :project, foreign_key: true
    belongs_to :user, foreign_key: true
end
class StaticPagesController < ApplicationController
  def home
    if logged_in?
      @project = current_user.projects.build
      @feed_items = current_user.feed.paginate(page: params[:page])
    end
  end

代码抛出错误:

<% if @user.projects.any? %>
    <h3>Projects (<%= @user.projects.count() %>)</h3>

错误是:

 SQLite3::SQLException: no such column: project_users.true: SELECT  1 AS one FROM "projects" INNER JOIN "project_users" ON "projects"."id" = "project_users"."true" WHERE "project_users"."user_id" = ? LIMIT ?
ruby activerecord many-to-many ruby-on-rails-5 associations
2个回答
0
投票

这是一个措辞糟糕的问题,正如评论所建议的那样,请包含错误消息,否则无法调试。

乍一看,我可以在您的架构中看到以下问题:

  1. 表以复数形式命名,例如
    project_users
  2. 外键采用单数形式,例如
    user_id
  3. 使用
    t.references :user
    助手代替
    t.integer :user_id
    。然后,您可以传递
    index: true, foreign_key: true
    选项来设置索引和外键。

0
投票

foreign_key: true 导致您的错误。 ProjectsUser 模型应该如下所示

class ProjectUser < ApplicationRecord
    belongs_to :project
    belongs_to :user
end

错误

SQLite3::SQLException: no such column: project_users.true
试图解释您设置模型的方式让sqlite在ProjectUser上寻找名为“true”的列。由于foreign_key列的名称与关联对象(项目和用户)的类名相同,因此您不需要专门告诉ActiveRecordforeign_key的名称。它会正确地假设它正在寻找project_id和user_id

© www.soinside.com 2019 - 2024. All rights reserved.