我正在开发一个人们组织游戏会话的项目。 (删节)模型如下。Activerecord:无法获取:通过=>上班
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>
编辑
比ks给Christopher Manning,我将reservations
更改为:reservations
,从而消除了微不足道的错误。但是,如果我现在尝试使用@user.reserved_events
Ø@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
使用:source => :events
使得它不惜一大家子缺少不同的列
我的临时解决方案是使用直接SQL:
@reserved_events = Event.find_by_sql("select events.* from events,reservations where events.id=reservations.event_id AND reservations.user_id="[email protected]_s)
更好的主意?
非常感谢!它应该是一件小事! – piffy