13

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?

denniss
  • 17,229
  • 26
  • 92
  • 141

1 Answers1

14

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.

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • wait a seconds, what would I put on the user model though? if I want to say user.created_events which returns the events that the user has created? – denniss Dec 23 '10 at 06:47
  • @denniss You can do this, but not with a `has_many :through`. – Jacob Relkin Dec 23 '10 at 06:52
  • how would I do it. or may be can you refer me to an article or tutorial that does this? – denniss Dec 23 '10 at 07:00
  • @denniss There is no way to do it via a `has_many :through`. If you can sacrifice the `:through`, then you can use `has_many :created_events, :class_name => "Event"` – Jacob Relkin Dec 23 '10 at 07:07
  • @JacobRelkin How did you determine that you cannot mix a has_many :through and a belongs_to to the same table? Is it documented somewhere or did you just figure it out? – Brian Deterling Feb 06 '13 at 22:01