簡體   English   中英

Ruby on Rails。 來自field_form的嵌套表單僅返回哈希,而不是數組的哈希

[英]Ruby on Rails. Nested form from field_form only return a hash instead of hash of array

我有一個嵌套的表單,我想將一個哈希值保存到field_form中,但是此哈希值僅將最后一個保存在params中。

這是我的控制器

def new
  @inventory_products   = []
  @inventory            = Inventory.new
  @products             = Product.all
  @products.each do |p|
    @inventory_products << p.inventory_products.build
  end
end

這是表格

<%= form_for @inventory do |f| %>
  <%= render 'shared/error_messages', object: f.object%>
  <%= f.label :description, "Description" %>
  <%= f.text_area :description, class: 'form-control' %>
  <%= f.label :warehouse, "Warehouse" %>
  <%= f.select :warehouse_id, options_for_select(Warehouse.all.map {
                              |b| [ b.name, b.id ] }),
                prompt: "foobar"%>
  <%= f.label :products, "Productos" %>
    <table class = "table table-bordered">
      <thead>
        <tr>
          <th>+</th>
          <th>Codigo</th>
          <th>Nombre</th>
          <th>Cantidad a Ingresar</th>
        </tr>
      </thead>
      <tbody>
        <% @inventory_products.each_with_index do |i, index|%>
      <%= f.fields_for "inventory_products[]", i do |iv|%>
        <tr>
          <td>
            <%= iv.check_box :product_id, {class: 'add_product',checked:false},iv.object.product_id.to_s, "0" %>
          </td>
          <td><%= @products[index].code %></td>
          <td><%= @products[index].name %></td>
          <td>
            <%= iv.number_field :quantity, class:"form-control quantity#{iv.object.product_id.to_s}", readonly: true %>
          </td>
        </tr>
      <% end %>
    <% end %>

庫存模型

class Inventory < ApplicationRecord
  has_many :inventory_products
  has_many :products, through: :inventory_products
  belongs_to  :warehouse
  accepts_nested_attributes_for :inventory_products
  validates:description, presence:true, length: {maximum:150}
end

庫存產品型號

class InventoryProduct < ApplicationRecord
  belongs_to  :product
  belongs_to  :inventory
  accepts_nested_attributes_for :product
  validates:quantity,  presence:true, numericality: { greater_than: 0}
end

產品型號

class Product < ApplicationRecord
  has_many :inventory_products
  has_many :inventories, through: :inventory_products
end

PARAMS

<ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"xwu4sCQCCCWOwXqbJkvVl9MDs2HRmjdT8IL2eMdMi0KHbibzHuQNmIWpot7fVqohvvxDlMIAEBzlDZB0OW3DCQ==", "inventory"=>{"description"=>"", "warehouse_id"=>"", "inventory_products"=>{"product_id"=>"1", "quantity"=>""}}, "commit"=>"Agregar", "controller"=>"inventories", "action"=>"create"}
def new
  @inventory            = Inventory.new
  @products             = Product.all
  @products.each do |p|
    @inventory << p.inventory_products.new(product: p)
  end
end

def create
  @inventory = Inventory.new(inventory_params)
  if @inventory.save
    # ...
  else
    # ...
  end
end

private

def inventory_params
  params.require(:inventory).permit(inventory_products_attributes: [:product_id, :quantity, :_keep])
end

無需手動遍歷記錄,您只需在關聯和rails上使用fields_for創建適當的參數:

<%= form_for(@inventory) do |f| %>
  <%= f.fields_for :inventory_products do |iv|%>
    <tr>
      <td>
        <%= iv.hidden_field :product_id %>
        <%= iv.check_box :_keep, { class: 'add_product', checked:false }%>
      </td>
      <td><%= iv.object.code %></td>
      <td><%= iv.object.name %></td>
      <td>
        <%= iv.number_field :quantity, class:"form-control quantity#{iv.object.product_id.to_s}", readonly: true %>
      </td>
    </tr>
  <% end %>
<% end %>

我們還引入了一個名為_keep的虛擬屬性,而不是使用帶有產品ID的復選框-這似乎過於復雜和棘手。

class InventoryProduct < ApplicationRecord
  belongs_to  :product
  belongs_to  :inventory
  attr_reader :_keep
  accepts_nested_attributes_for :product, reject_if: :not_acceptable?
  validates :quantity, 
     presence: true, 
     numericality: { greater_than: 0 }

  def _keep=(value)
    @_keep = typecast_to_boolean(value)
  end

  def not_acceptable?(attributes)
    !typecast_to_boolean( attributes[:_keep] )
  end

  private 

  def typecast_to_boolean(value)
    ActiveRecord::ConnectionAdapters::Column.value_to_boolean(value)
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM