[英]Rails Associations: SQLite3::SQLException: no such column
我有以下設置:
class Invite < ActiveRecord::Base
belongs_to :attending_guest, :class_name => "User", :foreign_key => :attending_guest_id
belongs_to :attending_event, :class_name => "Event"
end
class Event < ActiveRecord::Base
belongs_to :creator, :class_name => "User"
has_many :invites
has_many :attendees, :through => :invites, :source => :attending_event
end
class User < ActiveRecord::Base
has_many :created_events, :foreign_key => "creator_id", :class_name => "Event"
has_many :invites
has_many :attended_events, through: :invites, source: :attending_guest
end
以下架構:
ActiveRecord::Schema.define(version: 20151114095321) do
create_table "events", force: :cascade do |t|
t.string "title"
t.string "date"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "creator_id"
t.string "location"
end
add_index "events", ["creator_id"], name: "index_events_on_creator_id"
create_table "invites", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "attending_guest_id"
t.integer "attending_event_id"
end
add_index "invites", ["attending_event_id"], name: "index_invites_on_attending_event_id"
add_index "invites", ["attending_guest_id"], name: "index_invites_on_attending_guest_id"
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
創建此關系后,在鞋墊中,運行時出現以下錯誤:
2.2.0 :001 > u = User.first
User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 1, name: "User One", email: "user@example.com", created_at: "2015-11-14 09:20:26", updated_at: "2015-11-14 09:20:26">
2.2.0 :002 > u.attended_events
User Load (0.4ms) SELECT "users".* FROM "users" INNER JOIN "invites" ON "users"."id" = "invites"."attending_guest_id" WHERE "invites"."user_id" = ? [[nil, 1]]
SQLite3::SQLException: no such column: invites.user_id: SELECT "users".* FROM "users" INNER JOIN "invites" ON "users"."id" = "invites"."attending_guest_id" WHERE "invites"."user_id" = ?
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: invites.user_id: SELECT "users".* FROM "users" INNER JOIN "invites" ON "users"."id" = "invites"."attending_guest_id" WHERE "invites"."user_id" = ?
誰能解釋這是怎么回事? 我已經嘗試了許多不同的方法,但是無法理解問題出在什么地方。任何幫助將不勝感激! 謝謝一群!
該錯誤表明您的invites
沒有user_id
列。
按照慣例,Rails假定用於保留其他模型上的外鍵的列是該模型的名稱,並添加了后綴_id。 :foreign_key選項可讓您直接設置外鍵的名稱
因此,您可以添加:
class User < ActiveRecord::Base
has_many :invites, :foreign_key => :attending_guest_id
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.