Accessing parent object attribute from child's object in Rails

后端 未结 2 1929
渐次进展
渐次进展 2020-12-17 17:46

I have a model called Category which looks like this:

class Category < ActiveRecord::Base
  has_many :categories
  belongs_to :category,:foreign_key =>         


        
相关标签:
2条回答
  • 2020-12-17 18:07

    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.

    0 讨论(0)
  • 2020-12-17 18:21

    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,...

    0 讨论(0)
提交回复
热议问题