【发布时间】:2014-07-01 11:48:21
【问题描述】:
我是 Rails 新手,不知道如何使用 HABTM 关系显示数据。 1.情况是我正在尝试创建简单的工具,其中我有分配了型号的设备,每个型号都可以有特定的备件。 2. 我已经成功地创建了HABTM 关系和表,以将模型分配给备件并将其保存到数据库中。 2. 我希望能够为设备创建工单,在创建工单期间用户应该能够订购备件(但只能从该特定型号设备的零件列表中订购!)。 3. 我在创建工单时卡住了如何仅显示特定设备型号的部件(我确实将 model_id 作为 url 中的参数传递)。可能毕竟要将它保存到数据库中,我需要使用额外的 HABTM 表 ticket_parts 但现在我只想知道如何显示它。 4. 我得到未定义的方法“模型”#
非常感谢您对此问题的建议和帮助!
模型看起来像:
class Model < ActiveRecord::Base
has_and_belongs_to_many :parts
accepts_nested_attributes_for :parts
end
class Device < ActiveRecord::Base
belongs_to :model
end
class Part < ActiveRecord::Base
has_and_belongs_to_many :models
has_and_belongs_to_many :order_tickets
accepts_nested_attributes_for :models
end
我的票/_form.html.erb 看起来像:
<%= form_for(@ticket) do |f| %>
<% if @ticket.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@ticket.errors.count, "error") %> prohibited this ticket from being saved:</h2>
<ul>
<% @ticket.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :counter %><br>
<%= f.number_field :counter %>
</div>
<div class="field">
<%= f.label :issue %><br>
<%= f.text_area :issue %>
</div>
<!-- Here i want to display the spare parts only for the specific model -->
<% Part.models(:model_id).each do |x| %>
<%= x.name %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
【问题讨论】:
标签: ruby-on-rails has-and-belongs-to-many