Rails - Virtual attribute in form helper

1.5k views Asked by At

I'm having an odd error with a virtual attribute in a form helper.

My model looks like this:

class Folder < ActiveRecord::Base
 ...
  # VIRTUAL ATTRIBUTES
  def parent_name
   self.parent.name
  end

  def parent_name=(name)
    self.parent = self.class.find_by_name(name)
  end
  ...
end

I'm using HAML and SimpleForm. When I use my form like this...

= simple_form_for [@collection, form], :html => { :class => 'full' } do |f|
  = f.input :name
  = f.input :description
  = f.submit

... it works perfectly. But if I try to access the virtual attribute like so...

= simple_form_for [@collection, form], :html => { :class => 'full' } do |f|
  = f.input :name
  = f.input :parent_name
  = f.input :description
  = f.submit

... I get this error:

NoMethodError in Folders#index

Showing ... where line #3 raised:

undefined method `name' for nil:NilClass

Extracted source (around line #3):

1: = simple_form_for [@collection, form], :html => { :class => 'full' } do |f|
2:  = f.input :name
3:  = f.input :parent_name
4:  = f.input :description
5:  = f.submit

Any suggestions?

2

There are 2 answers

1
sled On BEST ANSWER

Try this:

def parent_name
 self.parent.nil? ? nil : self.parent.name
end

Problem is, that the it tries to access the name of the "parent" which doesn't exist. So parent is at this point Nil object and you're trying to access the attribute "name" of a Nil object -> Fails

Edit: maybe it's more suitable to return an empty string like:

self.parent.nil? ? "" : self.parent.name
0
patrickmcgraw On

It looks like that error message is saying that

self.parent

is returning nil inside

def parent_name