rails model has_many of itself

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


You will want to change your has_many to something like this:

has_many :parent_events, class_name: 'Event'
has_many :child_events, ->(event) { where parent_event_id: event.id }, class_name: 'Event'

This is from the rails 4 docs at the link: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Specifically, the section on "customizing the query". This should allow you to do what you're looking for. Didn't try it locally, but this is similar to what I had to do to implement a football pickem app I did a while back.

Hope this helps.


Try Nested Set Pattern

For this one: Awesome Nested Set