我是新手,我对如何在视图中正确显示嵌套模型属性略有困惑。在我的节目视图中正确显示嵌套模型
我正在使用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 %>
? :)
我对我的模型和控制器进行了更改,但是现在在我的show view上放置引擎的正确语法是什么? 谢谢! – Morphiuz
通过<%@ company.vehicles.engines调用它|引擎| %>给我不明确的方法引擎 – Morphiuz
是的,给我几分钟 – achempion