has_many形式,具有现有对象的嵌套属性

时间:2013-08-28 19:46:42

标签: ruby-on-rails nested-attributes has-many

我仍然是Rails的新手,并且相当确定我试图解决这个问题的方式效率低下或者只是愚蠢,但这就是我想要完成的事情。我有2个模型,案例(病例档案)和库存(案例中使用的医疗移植材料)。

class Case < ActiveRecord::Base
  has_many :inventories
  accepts_nested_attributes_for :inventories, :reject_if => :all_blank
end

class Inventory < ActiveRecord::Base
  belongs_to :case
end

通过单独的流程创建库存,目标是通过案例表单将它们与案例相关联。我要做的是在我的Case表单上放置一个表格,列出可用的库存以及复选框,以选择与要创建的案例关联的所需库存。由于我需要能够在每个Inventory上包含几个属性的嵌套字段(:case_price和:case_ship_price),这使事情变得更加复杂。我之前使用has_many通过关联并将这些属性存储在数据透视表上以非常迂回的方式执行此操作,但它涉及一些hacky代码以捕获来自params的字段输入,然后通过此块保存它们:

class CasesController < ApplicationController
  def create
    @case = Case.new(params[:case])
    if @case.save
      @case.case_lineitems.each do |li|
        li.update_attributes(:price => params[:lineitem_price][li.inventory_id.to_s],
                             :shipping_cost => params[:lineitem_shipping][li.inventory_id.to_s])
      end
      redirect_to @case
    else
      render 'new'
    end
  end
end

这感觉非常笨拙,我担心它可能造成的问题,所以我想尝试一个简单的has_many,belongs_to关系。但是,我不确定典型的<%= check_box_tag :inventory_ids, inventory.id, @case.inventories.include?(inventory), name: 'case[inventory_ids][]' %>是否适用于这种类型的关系。以下是我目前表格的这一部分:

<table>
  <thead>
    <tr>
      <th></th>
      <th>Product</th>
      <th>Serial #</th>
      <th>Price</th>
      <th>Shipping</th>
    </tr>
  </thead>
  <tbody>
    <% @inventories.each do |inventory| %>
      <tr>
        <td>
          <%= check_box_tag :inventory_ids, inventory.id, @case.inventories.include?(inventory), name: 'case[inventory_ids][]' %>
        </td>
        <td><%= inventory.product.name %></td>
        <td><%= inventory.serial_num %></td>
        <%= f.fields_for :inventories, inventory do |inv| %>
          <td>
            <%= inv.text_field :case_price %>
          </td>
          <td>
            <%= inv.text_field :case_ship_price %>
          </td>
        <% end %>
      </tr>
    <% end %>
  </tbody>
</table>

这导致第一个复选框默认为已选中,如果我全部取消选中,则所有库存在提交时都会关联。仅检查子集会导致Couldn't find Inventory with ID=206 for Case with ID=行的异常。最后,检查所有库存似乎会导致关联和嵌套属性正确保存。

如何清理它以使其按预期工作?如果我需要回到has_many通过关系,是否有更好的方法在数据透视表上保存属性,在创建数据透视表上的行的同一表单上?我真的很感激任何帮助,因为没有多少搜索让我摆脱这一挑战。

0 个答案:

没有答案
相关问题