如何在Rails中从子项创建父项?

时间:2012-10-16 01:13:17

标签: ruby-on-rails nested-forms

在我的应用中,我收到此错误。

  

对于ID为

的InventoryItem,找不到ID = 1的供应商

InventoryItem.rb

belongs_to :vendor
accepts_nested_attributes_for :vendor

Vendor.rb

has_many :inventory_items

_form.html.erb

<%= simple_nested_form_for @inventory_item, :html => {:class => 'form-inline' } do |f| %>                                                                                     


  <h2>Inventory Data</h2>
  <%= f.input :name, :input_html => {:autocomplete => :off, :placeholder => 'Item Name' }%> 
    <%= f.input :id, :as => :hidden %>

    <%= f.simple_fields_for :vendor do |v| %>
      <%= v.input :name, :label => 'Vendor name', :input_html => {:autocomplete => :off, :placeholder => 'Vendor Name' } %>
      <%= v.input :id, :as => :hidden %>
    <% end %>
<% end %>
  ----snip----

我的参数哈希相应地出现

{"utf8"=>"✓",
 "authenticity_token"=>"ZY9fum4XGStTMNbpRQxrzmP7PT3A6BUU+wOymV0fZ/c=",
 "inventory_item"=>{"name"=>"testing",
 "id"=>"7678",
 "vendor_attributes"=>{"name"=>"test",
 "id"=>"1"},
 "item_instances_attributes"=>{"0"=>{"barcode"=>"",
 "funding_source"=>"",
 "serial"=>"",
 "version"=>"",
 "website_id"=>"",
 "item_type"=>"Retail",
 "type_of_at"=>"Vision",
 "os"=>"Mac",
 "registration_key"=>"",
 "dealer_price"=>"",
 "retail_price"=>"",
 "reuse_price"=>"",
 "estimated_current_purchase_price"=>"",
 "cost_to_consumer_for_loan"=>"",
 "repair_status"=>"Working",
 "date_reviewed"=>"10-15-2012",
 "qr_url"=>"",
 "location"=>"",
 "restrictions"=>"",
 "notes"=>""}}},
 "commit"=>"Create Inventory item"}

inventory_items_controller.rb

def create
    params[:inventory_item].delete(:estimated_dealer_price)
    @inventory_item = InventoryItem.create(params[:inventory_item])
    @inventory_item.name = inventory_item.name.downcase

    if inventory_item.save
      redirect_to(inventory_items_path, :notice => "Item created.")
    else
      render 'new'
    end 
  end 

控制器正在接收id并尝试找到合适的供应商(存在),在找到供应商和建立关系的内置rails方法时会出现问题。

供应商名称的输入是自动完成,它将id分配给隐藏的id字段。

可能的解决方案:

  1. 在控制器中手动处理,获取ID并建立关系
  2. 更改表单,以便inventory_item.vendor.name自动填充inventory_item.vendor_id并在提供ID时删除名称
  3. 修复我遗失的东西?

1 个答案:

答案 0 :(得分:0)

听起来你反过来了,通常孩子不应该创建父记录,你应该检查它是否可以使其更符合父子关系的标准方法。

据说你可以做这样的事情

InventoryItem << ActiveRecord::Base
  belongs_to :vendor
  def vendor_attributes=(params)
    self.vendor = Vendor.find(params[:id]) || Vendor.create_by_name!(params[:name])
  end
end