我正在開發一個人們組織遊戲會話的項目。 (刪節)模型如下。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