ユーザーとプロジェクトを関連付けるときに has_many による関連付けエラーが発生する
概要
2つのモデル、つまりユーザーとプロジェクトの間の多対多の関係に has_many :through association を使用しましたが、多対一の関係でうまく機能したクエリがエラーをスローしているため、それには何らかの間違いがあるようです。誰かチェックしてもらえませんか!スキーマファイルは以下のとおりです。
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、経由::project_users デフフィード プロジェクト 終わり 終わり
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 ?
解決策
コメントで示唆されているように、これはひどい言葉遣いの質問です。エラー メッセージを含めてください。そうしないとデバッグできません。
一目見ただけで、スキーマに次の問題があることがわかります。