楷模:
class Car < ActiveRecord::Base
...
belongs_to :manufacturer
...
end
class Manufacturer < ActiveRecord::Base
...
has_many :cars
...
end
汽车控制器:
def index
@title = "All cars"
@cars = Car.paginate(:page => params[:page], :per_page => 20)
end
看法:
<%= car.manufacturer.name %>
显示:nil:NilClass 的未定义方法“名称”
好的。看法:
<%= car.manufacturer[name] %>
显示:#<#:0x460c488> 的未定义局部变量或方法“名称”
但!看法:
<%= car.manufacturer.to_yaml %>
显示:
--- !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
那么如何读取 Car.manufacturer 的名称?