我是新的轨道,我如何正确地在视图中显示嵌套模型属性略有困惑。
我使用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泛音在嵌套形式这些模型。 在这里,companies_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 %>
?? :)