从Rails中的子对象访问父对象属性

Nob*_*ita 11 model ruby-on-rails foreign-keys

我有一个名为Category的模型,如下所示:

class Category < ActiveRecord::Base
  has_many :categories
  belongs_to :category,:foreign_key => "parent_id"
end
Run Code Online (Sandbox Code Playgroud)

我有一个视图,显示具有一些属性的所有类别.我可以访问category.parent_id,但我希望能够做类似的事情category.parent_name.
我可以看到自己创建一个模型方法来获取所有类别并使用每个类别的对应父级名称填充集合,但我想知道是否有任何方式可以轻松地执行此操作.

编辑:我修改了模型,让它像这样:

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
Run Code Online (Sandbox Code Playgroud)

创建表类别的迁移如下所示:

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :name
      t.text :description
      t.integer :parent_id

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是,当我将类别对象传递给视图时,我无法通过执行来访问其父属性category.parent.name- 执行inspect该对象时,我会:

<Category id: 2, name: "Test 2", description: "Prova 2", parent_id: 1, created_at: "2012-01-17 19:28:33", updated_at: "2012-01-17 19:28:33">
Run Code Online (Sandbox Code Playgroud)

如果我检查category.parent我得到这个:

#<Category id: 1, name: "Prova", description: "Test", parent_id: nil, created_at: "2012-01-17 19:28:17", updated_at: "2012-01-17 19:28:17">
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试这样做,category.parent.name我会收到以下错误:

undefined method `name' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

EDIT2:我试图在我上面提到的对象之前访问一个nil的父级.这样做:

category.parent.try(:name) 
Run Code Online (Sandbox Code Playgroud)

正如Michael Irwin所建议的那样,其中一个答案解决了它.

dav*_*idb 13

自我引用协会在第一次很难......

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
Run Code Online (Sandbox Code Playgroud)

然后你可以调用category.children并且category.parent还可以访问相关的oobjects的所有属性,...


Mic*_*win 8

我不确定我完全理解你的问题,但category.parent.name应该有效.如果某个类别没有父母,请执行类似category.parent.try(:name)避免获取的内容NoMethodError.