0

我正在从事一个人们组织游戏会议的项目。(删节)模型如下。

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_eventso @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)

更好的想法?

4

2 回答 2

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 字段。让我知道您对此有什么问题。

于 2012-06-04T01:27:12.313 回答
0

换成reservations:reservations

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

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

于 2012-06-03T22:16:29.933 回答