2012-06-03 36 views
0

我正在开发一个人们组织游戏会话的项目。 (删节)模型如下。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)

更好的主意?

回答

0

变化reservations:reservations在线路

has_many :reserved_events, :class_name => 'Event',:through => reservations 

固定未定义局部变量或方法的错误。

+0

非常感谢!它应该是一件小事! – piffy

0

试试这个:

class User < ActiveRecord::Base 
    has_many :events, dependent: :destroy 
    has_many :reservations, :through => :events 
end 

class Event < ActiveRecord::Base 
    belongs_to :user 
    has_many :reservations, dependent: :destroy 
end 

class Reservation < ActiveRecord::Base 
    belongs_to :events 
end 

这应该让你说:

@user.reservations 

事件应该有一个USER_ID领域。预订应该有一个event_id字段。让我知道你得到什么问题。

+0

嗯,它的工作,有点,但它不能解决我的问题。现在我发现了一个“Just works”解决方案,它是一个普通的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)'。这不是“Raily”,但它是一个单行的,现在它符合法案。 ' – piffy