[英]Rails Model Associations with has_many, through, class_name and where clause
Looking for a little help with rails associations. 寻找有关Rails协会的帮助。 I have three Models.
我有三个模型。 User, Attendee and Meeting and I would like to return a users attending Meetings based on their roles (which is under the attendee model).
用户,与会者和会议,我想根据其角色(在与会者模型下)返回参加会议的用户。 However I can't figure out how to return the user with a where clause.
但是我不知道如何通过where子句返回用户。
My code currently returns the Attendee
and then I look up the User
object but I would love it if there was I way I could make it return the User
object without having to look it up after the call. 我的代码当前返回了
Attendee
,然后我查找了User
对象,但是如果可以的话,我可以使它返回User
对象而不必在调用后查找它,我会喜欢它。
class Meeting
has_one :owner, -> { where role: 'owner' }, class_name: 'Attendee'
has_one :mentor, -> { where role: 'mentor' }, class_name: 'Attendee'
has_many :mentees, -> { where role: 'mentee' }, class_name: 'Attendee'
end
The other associations I have are as follows 我拥有的其他关联如下
has_many :users, through: :attendees
has_many :attendees, dependent: :destroy
Is this possible? 这可能吗? Any input is greatly appreciated.
任何输入,不胜感激。
I am not sure I understood you correctly. 我不确定我是否正确理解您。 Have you tried this and is this what you need?
您尝试过了吗,这是您所需要的吗?
class Meeting
has_one :owner, -> { where role: 'owner' }, class_name: 'Attendee'
has_one :mentor, -> { where role: 'mentor' }, class_name: 'Attendee'
has_many :mentees, -> { where role: 'mentee' }, class_name: 'Attendee'
has_one :owner_user, through: :owner, source: :user
has_one :mentor_user, through: :mentor, source: :user
has_many :mentees_users, through: :mentees, source: :user
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.