如何设置多个别名两种模式之间的连接? [英] How to set up multiple aliased joins between two models?

查看:75
本文介绍了如何设置多个别名两种模式之间的连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Rails 3.2应用程序,我需要设置两个协会的相同的两个模型之间。

In a Rails 3.2 app I need to set up two associations between the same two models.

例如

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

这是我第一次尝试用别名类名,而我无法得到它的工作。我不知道如果问题我是如何定义的关联,或其他地方所在。

This is the first time I've experimented with aliasing class names, and I'm having trouble getting it to work. I'm not sure if the issue lies with how I've defined the associations, or elsewhere.

难道我联想一下好不好?难道我忽略了需要得到这个工作什么?

Do my associations look OK? Have I overlooked something needed to get this to work?

我遇到的问题是,没有任何用户ID的考勤模式被设置。这可能是一个愚蠢的问题,但鉴于我上述的关联,如果字段名称是:user_ID的?或:event_organizer_id

The problem I'm having is that no user ids are being set in the Attendance model. This may be a stupid question, but given my associations above, should the field name be :user_id or :event_organizer_id?

真的AP preciate有这方面的建议。谢谢!

Really appreciate any suggestions on this. Thanks!

推荐答案

foreign_key在用户和事件中指定

foreign_key to be specified in User and Event

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

这篇关于如何设置多个别名两种模式之间的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆