【问题标题】:Rails Displaying data form HABTM realationshipRails 显示来自 HARM 关系的数据
【发布时间】: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


    【解决方案1】:

    在控制器的实例变量中检索模型,然后以你可以使用的形式:

    <% @model.parts.each do |x| %>
        <%= x.name %>
      <% end %>
    

    注意:“模型”不是保留字,但我建议不要将其用作类名。

    【讨论】:

    • 我已经把 def commonstuff @model = Model.find(params[:model_id]) end 放在票控制器和 before_action :commonstuff 中。但现在得到:nil:NilClass 的未定义方法 `parts'
    • 您好,那么您应该检查数据库中的模型实例是否与您传递的 id 值匹配。
    • 是的,我匹配。当我只想使用 打印模型变量时,我观察到了其他东西,它仍然显示 Nil,所以我想它会导致问题......
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多