在关联用户和项目时has_many通过关联错误

时间:2018-12-20 12:57:05

标签: ruby activerecord many-to-many ruby-on-rails-5 associations

我已经使用has_many:through关联来处理用户和项目这两个模型之间的多对多关系,但是似乎存在一些错误,因为在多对一关系中运行良好的查询是引发错误。有人可以检查一下!模式文件如下:

    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文件包含以下代码:

类用户

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 ?

1 个答案:

答案 0 :(得分:0)

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

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

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