首页 > 解决方案 > form_tag:在 params[] 中保留许多 text_filed_tag 的值

问题描述

我有以下form_tag:

  - @invoice_data.each do |data|
    %br
    = label_tag "Description"
    %br
    = text_field_tag 'item[description]', data.position
    %br
    = label_tag 'Quantity'
    %br
    = text_field_tag 'item[quantity]', data.num_event
    %br
    = label_tag 'Single Preis'
    %br
    = text_field_tag 'item[single_preis]', data.billable_fees / data.num_event
    %br
    = label_tag 'Vat Percent'
    %br
    = text_field_tag 'item[vat_percent]', "19"
  %br
  %div
    %br
    = submit_tag "add", class: 'btn btn-sm btn-default', style: 'margin-left: 5px; margin-top: -2px', type: 'submit'

form_tag正在创建与 @invoice_data 中的记录数一样多的字段(这是查询的结果),但在提交我的params[]后仅存储@invoice_data的最后一条记录:<ActionController::Parameters {"utf8"=>"✓&quot;, "item"=><ActionController::Parameters {"description"=>"Payment 4", "quantity"=>"1", "single_preis"=>"$0.26", "vat_percent"=>"19"} permitted: true>, "commit"=>"add", "controller"=>"comercio", "action"=>"send_invoice", "id"=>"1"} permitted: true>

我应该怎么做才能将 @invoice_data 中的所有记录存储在 params[] 中,而不仅仅是最后一个?

非常感谢您!

标签: ruby-on-railsrubyformshaml

解决方案


Rails 创建 necord 和嵌套子级的方法是使用嵌套属性:

class Invoice < ApplicationRecord
  has_many :items
  accepts_nested_attributes_for :items
end

class Item < ApplicationRecord
  belongs_to :invoice
end
= form_with(model: @invoice) do |form|
  = form.fields_for :items do |item|
    = item.text_field :description
    = item.nhumber_field :quantity

处理从查询到项目实例的任何类型的疯狂映射不是您视图的工作。它应该在其他地方处理,例如控制器或服务对象:

class InvoicesController
  def new  
    invoice_data = get_it_from_somewhere
    @invoice = Invoice.new do |i|
      invoice_data.each do |raw|
        i.items.new(
          description: data.position,
          # ...
        )
      end
    end   
  end

  def create 
    @invoice = Invoice.new(invoice_params)
    if @invoice.save
      redirect_to @invoice
    else
      render :new
    end
  end

  private 
  
  def invoice_params
    params.require(:invoice)
          .permit(:foo, :bar, items_attributes: [ :description, :quantity, ...])
  end
end

推荐阅读