我是 Rails 新手,我对如何在视图中正确显示嵌套模型属性有些困惑。
我正在使用 Rails 3.2.6。
我在这里的3个模型:
class Company < ActiveRecord::Base
attr_accessible :name, :vehicles_attributes, :engines_attributes
has_many :vehicles, :dependent => :destroy
accepts_nested_attributes_for :vehicles, :allow_destroy => true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
class Vehicle < ActiveRecord::Base
attr_accessible :company_id, :engines_attributes
belongs_to :company
has_many :engines, :dependent => :destroy
accepts_nested_attributes_for :engines, :allow_destroy => true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end
class Engine < ActiveRecord::Base
attr_accessible :make, :model, :model_year, :vehicle_id
belongs_to :vehicle
end
我使用 simple_form_for 和 simple_fields_for 部分将这些模型置于嵌套形式中。这里是company_controller.rb
def show
@company = Company.includes(vehicles: :engines).find(params[:id])
#added this, thanks to @achempion
...
end
def new
@company = Company.new
@company.addresses.build
@company.vehicles.build
...
end
我的节目视图:
<% for vehicle in @company.vehicles %>
<p>Make: <strong><%= h vehicle.make %></strong></p>
<p>Model: <strong><%= h vehicle.model %></strong></p>
<p>Odometer Reading: <strong><%= h vehicle.odometer %></strong></p>
<p>Vehicle ID No. (VIN): <strong><%= h vehicle.vin %></strong></p>
<p>Year: <strong><%= h vehicle.year %></strong></p>
<% end %>
但是我如何像处理车辆一样在循环中引用公司 -> 车辆 -> 引擎?我总是乐于接受建议!
目前我已经用@company.vehicles.engines 尝试了一堆语法,但我不断得到
undefined method `engines' for #<ActiveRecord::Relation:0x007fd4305320d0>
我确定只是我不熟悉控制器和显示视图中的正确语法。
任何帮助表示赞赏=)
另外,是否有更好的方法来执行该循环?也许
<%= @company.vehicles.each |vehicle| %>
<%= vehicle.make %>
...
<% end %>
?? :)