如何在两个模型之间设置多个别名连接?

时间:2012-06-05 13:52:29

标签: ruby-on-rails-3 activerecord

在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

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

我的协会看起来不错吗?我是否忽略了让它发挥作用所需要的东西?

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

真的很感激有关这方面的任何建议。谢谢!

1 个答案:

答案 0 :(得分:1)

要在用户和事件中指定的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