Rails has_many : 通过关联 [英] Rails has_many :through association

查看:54
本文介绍了Rails has_many : 通过关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 rails 应用程序,用户可以在其中创建事件并邀请参与者加入,并需要您的帮助!我一直在兜圈子,尝试了几件事,但似乎根本不对,现在这让我发疯了!!我正在使用 Rails 4.

I'm trying to create a rails app where user can create events and invite participants to it and need your help! I've been going in circle, trying few things but doesn't seem right at all and this is now driving me crazy!! I'm using rails 4.

您将如何设置活动模型?

How would you setup the active model?

User
has_many :events through :meeting   //for the participants?
has_many :events     // for the organizer?

Event
belongs to :user
has_many :participants, class_name: "User"


Participant
belongs to :user
has_many :events through :meeting

Meeting
has_many :participants
has_many :events

这样有意义吗?我需要参与者模型还是我只是过度设计了它?我想我有点困惑组织者是用户,参与者也是用户,会议需要组织者和参与者,所以不太清楚如何使这项工作...

Does that make any sense? Do I need the Participant Model or am I just over-engineering it? I guess I'm a bit confused with organizer is a user and participants are also users and meeting needs both organizer and participants so not so clear how to make this work...

另请阅读我只能在添加参与者后建立会议关系.这是要走的路吗?谢谢!

Also read I could build the meeting relationship only when participant has been added. Would that be the way to go? Thank you!

推荐答案

首先,您不需要参与者模型.如果我想在会议模型中存储一些额外的信息,这就是我将使用的结构.如果没有,您可以直接使用 has_and_belongs_to_many.

First of all you don't need a participant model. This is the structure I'll use if there is some extra information I want to store in the meeting model. If not you can directly use has_and_belongs_to_many.

User
has_many :meetings
has_many :attending_events, through: :meetings, source: "Event"   //for the participants
has_many :events     // for the event organiser

Event
belongs to :user // The organiser
has_many :meetings
has_many :participants, through: :meetings, source: "User"  

Meeting
belongs_to :participant, class_name: "User"
belongs_to :attending_event, class_name: "Event" // Use attending_event_id as foreign_key

这篇关于Rails has_many : 通过关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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