【发布时间】:2018-12-20 12:57:05
【问题描述】:
我使用 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 文件包含代码:
类用户 project_user.rb 文件有代码: 错误是代码抛出的: 错误是:The project.rb file has the code:
class Project < ApplicationRecord
has_many :project_users
has_many :users, :through => :project_users
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 ?
【问题讨论】:
-
编辑您的问题以添加模型的相关部分、引发错误的代码以及(当然)确切的错误消息。
-
它会抛出什么错误?这是非常基本的调试信息。
-
Remove
foreign_key: true外键是一个非常规外键的名称,在您的关联中不是这种情况
标签: ruby activerecord many-to-many ruby-on-rails-5 associations