我有以下设置:
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
创建此关系后,在cnosole中,运行时出现以下错误:
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" = ?
有谁可以解释发生了什么?我尝试了很多不同的东西但是无法理解问题是什么......任何帮助都会非常感激!非常感谢!
答案 0 :(得分:1)
此错误表明您在user_id
中没有invites
列。
按照惯例,Rails假定用于在另一个模型上保存外键的列是此模型的名称,并添加了后缀_id。 :foreign_key选项允许您直接设置外键的名称
所以你可以补充一下:
class User < ActiveRecord::Base
has_many :invites, :foreign_key => :attending_guest_id
end