레일스를 처음 사용 했으므로 뷰에 중첩 모델 특성을 올바르게 표시하는 방법에 대해 약간 혼란 스럽습니다.내 쇼 뷰에 중첩 모델을 올바르게 표시합니다.
레일 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 %>
?? :)
내 모델 및 컨트롤러를 변경했지만 지금은 내 쇼 뷰에 엔진을 배치하는 올바른 구문은 무엇입니까? 감사합니다. – Morphiuz
<% @ company.vehicles.engines do | engines |를 통해 전화하십시오. %> 정의되지 않은 메소드 엔진을 제공합니다. – Morphiuz
예, 몇 분만 응답하십시오. – achempion