Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

ruby on rails - belongs_to and has_many to the same model

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 

and the user model looks something like

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

instead of

e.user

is there a way for me to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply pass some options to belongs_to:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...