rails model has_many of itself

≯℡__Kan透↙ 提交于 2019-11-28 21:06:57
derekyau

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.

Rails already has a gem for providing nested tree structure ancestry. It will be best in such scenarios:

https://github.com/stefankroes/ancestry

You will be able to access following methods:

event.parent
event.children
event.siblings

I found that in Rails 5 the belongs to has become mandatory by default so couldn't save my model instances... adding optional to the first line of the recommended solution fixes this...

class Event < ActiveRecord::Base
  belongs_to :parent, :class_name => "Event", :foreign_key => "parent_event_id", optional: true
  has_many :child_events, :class_name => "Event", :foreign_key => "parent_event_id"
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!