Accessing parent object attribute from child's object in Rails

元气小坏坏 提交于 2019-11-29 06:36:15

Self referencing associations are hard at the first time...

class Category < ActiveRecord::Base
  has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'
  belongs_to :parent, :class_name => 'Category', :foreign_key => 'parent_id'
end

Then you could call category.childrenand category.parent and also access all the attributes of the asscoiated oobjects,...

I'm not sure I completely understand your question, but category.parent.name should work. If a category doesn't have a parent, do something like category.parent.try(:name) to avoid getting a NoMethodError.

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