ruby-on-rails - 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"=>"✓", "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[] 中,而不仅仅是最后一个?
非常感谢您!
解决方案
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
推荐阅读
- pandas - Pandas 数据透视表:如何限制列仅显示一年的数据?
- spring-boot - sleuth 与 jms 的 Spring Boot 集成
- java - Swagger codegen - 自定义 Java 构造函数
- php - 如何在php后台运行python网络爬虫
- xml - Tomcat 8.5 server.xml 仅支持“org.apache.coyote.http11.Http11AprProtocol”的 All Host 的 defaulthost 的 SSLHostConfig
- javascript - Ember.js 是否可以为转换对象的数据属性分配任何值?
- c++ - 静态地图超出堆栈
- python - 如何从 matplotlib 图表的饼图中删除无?
- python - 如果键包含字符串列表中的字符串,则从字典列表中删除条目
- database - 我是否正确规范了这张表