属于同一模型的belongs_to 和has_many [英] belongs_to and has_many to the same model

查看:21
本文介绍了属于同一模型的belongs_to 和has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法用 Rails 做到这一点.基本上我有一个用户模型和一个事件模型.事件是由用户创建的,我希望在事件模型中有一个外键 (user_id) 来指示谁创建了事件.此外,事件可以有很多用户参加,因此事件模型变得类似于

I am wondering whether there is a way to do this with rails or not. Basically I have a user model and an event model. Event is created by a user and I want to have a foreign key (user_id) in the event model that indicates who created the event. Additionally, event can have many users who attend it so the event model becomes something like

belongs_to :user
has_many :users, :through => :guests #suppose i have the guest model 

用户模型看起来像

has_many :events, :through => :guests

我还没有尝试过这个关联,但我想说

I have not tried this association yet but I want to be able to say

e = Event.find(1)
e.creator #returns the user who created this event

代替

e.user

有没有办法让我做到这一点?

is there a way for me to do this?

推荐答案

只需将一些选项传递给belongs_to:

Simply pass some options to belongs_to:

belongs_to :creator, :class_name => "User", :foreign_key => "user_id"

这指定 creator 方法将是一个 User 对象,引用 user_id 字段.

This specifies that the creator method will be a User object, referencing the user_id field.

这篇关于属于同一模型的belongs_to 和has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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