2

在 Rails 3.2 应用程序中,我需要在相同的两个模型之间设置两个关联。

例如

class User
  has_many :events
  has_many :attendances
  has_many :attended_events, through: :attendances
end

class Event
  belongs_to :event_organizer, class_name: "User"
  has_many :attendances
  has_many :attendees, through: :attendances, class_name: "User"
end

class Attendance
  belongs_to :attended_event, class_name: "Event"
  belongs_to :attendee, class_name: "User"
end

这是我第一次尝试使用别名类名,但我无法让它工作。我不确定问题是否在于我如何定义关联或其他地方。

我的关联看起来不错吗?我是否忽略了使其正常工作所需的一些东西?

我遇到的问题是在出勤模型中没有设置用户 ID。这可能是一个愚蠢的问题,但考虑到我上面的关联,字段名称应该是:user_id 还是:event_organizer_id?

非常感谢您对此的任何建议。谢谢!

4

1 回答 1

1

在 User 和 Event 中指定的 foreign_key

class User
  has_many :events

  has_many :attendances, foreign_key: :attendee_id
  has_many :attended_events, through: :attendances
end

class Event
  belongs_to :event_organizer, class_name: "User" 
  # here it should be event_organizer_id

  has_many :attendances, foreign_key: :attended_event_id
  has_many :attendees, through: :attendances
end

class Attendance
  belongs_to :attended_event, class_name: "Event" 
  # this should have attended_event_id

  belongs_to :attendee, class_name: "User"        
  # this should have attendee_id because of 1st param to belongs_to here is "attendee"
  # and same should be added as foreign_key in User model
  # same follows for Event too
end
于 2012-06-05T15:11:37.970 回答