korywka
korywka

Reputation: 7653

Cant get object attribute

Models:

class Car < ActiveRecord::Base
  ...
  belongs_to :manufacturer
  ...
end


class Manufacturer < ActiveRecord::Base
  ...
  has_many :cars
  ...
end

Car controller:

  def index
     @title = "All cars"
     @cars = Car.paginate(:page => params[:page], :per_page => 20)
  end

View:

<%= car.manufacturer.name %>

Shows: undefined method `name' for nil:NilClass

Ok. View:

<%= car.manufacturer[name] %>

Shows: undefined local variable or method `name' for #<#:0x460c488>

BUT! View:

<%= car.manufacturer.to_yaml %>

Shows:

--- !ruby/object:Manufacturer
attributes:
  id: 1
  name: Acura
  created_at: 2011-11-30 09:59:19.750976000 Z
  updated_at: 2011-12-06 10:38:46.569531000 Z

So how can i read name of Car.manufacturer?

Upvotes: 1

Views: 236

Answers (2)

Jonathan
Jonathan

Reputation: 11504

<%= car.manufacturer.name if car.manufacturer %> as some results will not have the attribute set, this ensures you only call the attribute getter method if it has been set.

Upvotes: 2

fl00r
fl00r

Reputation: 83680

<%= car.manufacturer.try(:name) %>

And you could be interested in Presenter pattern

Upvotes: 1

Related Questions