我正在从事一个人们组织游戏会议的项目。(删节)模型如下。
class User < ActiveRecord::Base
has_many :events, dependent: :destroy #events organized by user
has_many :reservations, dependent: :destroy
end
class Event < ActiveRecord::Base
belongs_to :user
has_many :reservations, dependent: :destroy
end
class Reservation < ActiveRecord::Base
belongs_to :events
belongs_to :users
end
这样,当我使用时@user.events
,正如预期的那样,我得到了用户组织的事件列表。
但我想要一个用户预订的事件列表,(使用类似的东西@user.reserved_events
,所以我将它添加到用户模型中:
has_many :reserved_events, :class_name => 'Event',:through => reservations
这打破了一切,我得到了一个神秘的
undefined local variable or method `reservations' for #<Class:0x00000003681048>
编辑
感谢 Christopher Manning,我改成reservations
了:reservations
,从而消除了小错误。但是,如果我现在尝试使用@user.reserved_events
o @user.reservations.count
,我会得到
Could not find the source association(s) :reserved_event or :reserved_events in model Reservation. Try 'has_many :reserved_events, :through => :reservations, :source => <name>'. Is it one of :events or :users?
遵守请求让我无处可去:如果我使用:source => :users
,我得到
SQLite3::SQLException: no such column: reservations.users_id: SELECT COUNT(*) FROM "events" INNER JOIN "reservations" ON "events"."id" = "reservations"."users_id" WHERE "reservations"."user_id" = 1
using:source => :events
使它在另一个缺失的列上犹豫不决
我的临时解决方案是使用直接 SQL:
@reserved_events = Event.find_by_sql("select events.* from events,reservations where events.id=reservations.event_id AND reservations.user_id="+@user.id.to_s)
更好的想法?