Ruby on rails Rails关联:SQLite3::SQLException:没有这样的列
我有以下设置:Ruby on rails Rails关联:SQLite3::SQLException:没有这样的列,ruby-on-rails,ruby,activerecord,associations,Ruby On Rails,Ruby,Activerecord,Associations,我有以下设置: 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 bel
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
创建此关系后,在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" = ?
有人能解释发生了什么事吗?我试过很多不同的方法,但就是不明白问题出在哪里。。。任何帮助都将不胜感激!非常感谢 此错误显示邀请中没有用户id列 按照惯例,Rails假定用于在另一个模型上保存外键的列是该模型的名称,并添加了后缀_id。:foreign_key选项允许您直接设置外键的名称 因此,你可以加上:
class User < ActiveRecord::Base
has_many :invites, :foreign_key => :attending_guest_id
end
为什么你使用自定义外键名而不遵循rails惯例?抱歉,主要原因是我想了解Active Record中所有可用选项的不同用法。这是一个很好的原因,你应该在你的问题中注意到。是的,这很有效,你的解释让我看到了发生的巨大变化,非常感谢你!
class User < ActiveRecord::Base
has_many :invites, :foreign_key => :attending_guest_id
end