Ruby on rails 3 如何在两个模型之间设置多个别名联接?

Ruby on rails 3 如何在两个模型之间设置多个别名联接?,ruby-on-rails-3,activerecord,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 :at

在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\u id还是:event\u organizer\u id


非常感谢您对这方面的任何建议。谢谢

要在用户和事件中指定的外键

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

您是否收到任何错误消息?您在这些模型上调用什么?我正在尝试在控制台中创建一个事件。当我检查已创建的相关出席人数时,用户id为零。我正在调用
Event.create(出席者id:[1,3,4],事件组织者:1)
。现在想一想,我应该在考勤模型上有
attendee\u id
,而不是user\u id,不是吗?我不确定,检查一下class name方法,文档告诉我它应该是这样的格式:class\u name=>“Comment'”是的,带有attender\u以获取外键的模型,您还可以使用:foreign_key方法在表上指定外键。太好了!谢谢你帮我澄清这一点,我很困惑!有一个问题,是否有必要在“has_many:attended_events”上定义
:class_name=>“Event”
?试着理解为什么
:class_name
是必需的,第一个参数是
attended_events
,因此它会查找您没有的model
attended Event
,而您的意思是
Event
,这就是为什么它是必要的。如果您遵循所有默认约定,那么您只需要将单个参数传递给这些has\u many,own\u to。在添加别名的那一刻,您需要告诉原始表名和外键这就是hanks@Amoi,我想我理解这一点。在我的例子中,我没有名为AttendedEvents的模型,所以我认为需要定义一个
:class_name
。您上面的示例并没有定义这一点(类用户,有很多:参与的事件)。我正在试图理解为什么?这很简单,请参见docs=>“:class\u name指定关联的类名。仅当无法从关联名推断出该名称时才使用它。So belling\u to:author默认情况下将链接到author类,但如果真正的类名是Person,则必须使用此选项指定它。”最后,它的所有命名公约游戏。在您的情况下,用户有多个:出席,存在出席,因此无需定义:class\u name,但出席表有出席者id(而不是用户id,因为您希望它作为出席者),因此需要定义外键定义用户有多个:出席的唯一需要(或主要)是您需要使用:Attentions在下一行,如通过。您不能致电@user.attents。