Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 221
denniss Avatar asked Dec 23 '10 06:12

denniss


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is a polymorphic association in rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.


1 Answers

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.

like image 129
Jacob Relkin Avatar answered Oct 23 '22 17:10

Jacob Relkin