Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

model - Accessing parent object attribute from child's object in Rails

I have a model called Category which looks like this:

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

I have a view which shows all the categories with some of their attributes. I can access category.parent_id, but I would like to be able to do something like category.parent_name.
I can see myself creating a model method to fetch all categories and filling the collection with the correspondent parent name of each category, but I'm wondering if there is anyway to do this easily.

EDIT: I have modified the model to have it like this:

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

The migration to create the table categories is like this:

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

However when I pass a category object to a view I am not able to access its parent attributes by doing category.parent.name - Doing an inspect of that object gives me:

<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">

And if I do an inspect of category.parent I get this:

#<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">

However if I try to do category.parent.name I get the following error:

undefined method `name' for nil:NilClass

EDIT2: I was trying to access a parent that was nil before the object that I mentioned above. Doing this:

category.parent.try(:name) 

as suggested by Michael Irwin in one of the answers solved it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...