Activerecord:无法获取:through =>上班

时间:2012-06-03 21:23:38

标签: ruby-on-rails ruby 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>

修改

感谢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

使用: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)

更好的想法?

2 个答案:

答案 0 :(得分:0)

将<{1}}更改为

行中的reservations
:reservations

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

答案 1 :(得分: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字段。让我知道你对此有什么问题。