Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails model has_many of itself

I have a event model. Events can have parent events, set from a column in the model (parent_event_id). I need to be able to do has_many :event on the model, so I can just do, for example, event.child_event or event.parent_event. But my googling hasn't worked out that well.

My Model:

class Event < ActiveRecord::Base     attr_accessible :days_before, :event_name, :event_date, :list_id, :recipient_email, :recipient_name, :parent_event_id, :is_deleted, :user_id      belongs_to :user     has_many :event_email     has_many :event end 

My Schema:

create_table "events", :force => true do |t|     t.datetime "event_date"     t.integer  "days_before"     t.string   "recipient_email"     t.integer  "list_id"     t.string   "recipient_name"     t.datetime "created_at",                         :null => false     t.datetime "updated_at",                         :null => false     t.integer  "user_id"     t.string   "event_name"     t.integer  "parent_event_id"     t.boolean  "is_deleted",      :default => false end 
like image 787
Alexander Forbes-Reed Avatar asked Sep 13 '13 17:09

Alexander Forbes-Reed


People also ask

What is self association in rails?

Self-referential association means we create a JOIN MODEL, such as Friendship, for example, which links another model, such as User to itself, so a user can have many friends (which are other users), and a friend can be befriended by a user ( a follower and a followed).

What is 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 .

Does every model need a controller rails?

Do I need a controller for each model? No, not necessarily. However, having one controller per RESTful resource is a convention for a reason, and you should carefully analyze why that convention isn't meeting your needs before doing something completely different.

What is polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.


1 Answers

This is a self-referential model, you can try something like this:

class Event < ActiveRecord::Base   belongs_to :parent, :class_name => "Event", :foreign_key => "parent_event_id"   has_many :child_events, :class_name => "Event", :foreign_key => "child_event_id" end 

That way, you can call @event.parent to get an ActiveRecord Event object and @event.child_events to get an ActiveRecord collection of Event objects

like image 150
derekyau Avatar answered Oct 07 '22 10:10

derekyau