【问题标题】:Correctly displaying nested models in my show view在我的显示视图中正确显示嵌套模型
【发布时间】:2012-09-07 16:16:27
【问题描述】:

我是 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 %>

?? :)

【问题讨论】:

    标签: ruby-on-rails-3 nested-forms nested-attributes


    【解决方案1】:

    我认为@company = Company.includes(vehicles: :engines).find(params[:id]) 这是一个好方法。查看更多here

    你的主模型必须忘记has_many :engines, :dependent =&gt; :destroy,因为它是用于车辆模型的。祝你好运!

    您还可以将引擎视为:

    @company.vehicles.each do |vehicle|
      vehicle.engines.each do |engine|
        puts engine.id
      end
    end
    

    编辑:修正小错别字。

    【讨论】:

    • 我对模型和控制器进行了更改,但现在将引擎放在我的显示视图上的正确语法是什么?谢谢!
    • 通过 给了我未定义的方法引擎
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2021-07-01
    • 2021-12-07
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多