在我的显示视图中正确显示嵌套模型 [英] Correctly displaying nested models in my show view
问题描述
我是Rails的新手,我对如何在视图中正确显示嵌套模型属性有些困惑.
I'm new to rails and I'm slightly confused on how to properly display nested model attributes in a view.
我正在使用Rails 3.2.6.
I'm using 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
I have these models in a nested form using simple_form_for and simple_fields_for partials. Here the 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 %>
但是如何像使用车辆一样循环引用公司->车辆->发动机? 我总是乐于接受建议!
but how do I reference company -> vehicles -> engines in a loop like I do with vehicles? I'm always open to suggestions!
目前,我已经使用@ company.vehicles.engines尝试了一堆语法,但是我一直在获得
Currently I've tried a bunch of syntax with @company.vehicles.engines but I keep getting
undefined method `engines' for #<ActiveRecord::Relation:0x007fd4305320d0>
我确定只是我不熟悉控制器以及显示视图中的正确语法.
I'm sure it's just me being unfamiliar on proper syntax in the controller and also in the show view.
感谢您的帮助=)
此外,也许有更好的方法来执行该循环吗?也许
Also, is there maybe a better way to do that loop? maybe
<%= @company.vehicles.each |vehicle| %>
<%= vehicle.make %>
...
<% end %>
?? :)
推荐答案
我认为@company = Company.includes(vehicles: :engines).find(params[:id])
是个好方法.查看更多此处
I thik that @company = Company.includes(vehicles: :engines).find(params[:id])
it's a good way. see more here
您的主模型必须忘记has_many :engines, :dependent => :destroy
,因为它是用于Vehicle模型的.祝你好运!
And your main model must forget has_many :engines, :dependent => :destroy
because it's for Vehicle model. Good luck!
,您还可以看到以下引擎:
and you also can see engines as:
@company.vehicles.each do |vehicle|
vehicle.engines.each do |engine|
puts engine.id
end
end
修正了小错别字.
这篇关于在我的显示视图中正确显示嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!