rails model has_many of itself

喜夏-厌秋 提交于 2019-11-30 06:45:24

问题


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

回答1:


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




回答2:


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.




回答3:


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



回答4:


Try Nested Set Pattern

For this one: Awesome Nested Set




回答5:


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


来源:https://stackoverflow.com/questions/18791874/rails-model-has-many-of-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!