belongs_to的和的has_many到相同型号 [英] belongs_to and has_many to the same model
问题描述
我想知道是否有一种方法有栏杆或没有做到这一点。基本上,我有一个用户模型和事件模型。事件是由用户创建的,我想在事件模型,表明谁创建的事件外键(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的
:
belongs_to :creator, :class_name => "User", :foreign_key => "user_id"
这指定创作者
方法将是一个用户
对象,引用 USER_ID
字段中。
This specifies that the creator
method will be a User
object, referencing the user_id
field.
这篇关于belongs_to的和的has_many到相同型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!