简体   繁体   English

条形码输入导轨

[英]Barcode input Rails

When I open Sale(new) form it has an input field for a barcode scanner and a button add to add product items to this sale. 当我打开销售(新)表格时,它具有条形码扫描仪的输入字段和添加按钮以向此销售添加产品。 As I understand it, if I connect a barcode scanner and focus on the input field it should automatically input readings from the barcode. 据我了解,如果我连接条形码扫描仪并专注于输入字段,它将自动输入条形码的读数。

Now I have these readings (hopefully) and once the add button is pressed I don't really know what to do. 现在我有了这些读数(希望如此),一旦按下添加按钮,我真的不知道该怎么办。 I understand that I need to search the db and find the item with the same barcode. 我了解我需要搜索数据库并找到具有相同条形码的物品。 But the thing that is confusing me is that my Sale (new) is not saved yet therefore I can't add this item to the SaleItem model because I don't know the ID of the current sale. 但是令我感到困惑的是,我的Sale(新商品)尚未保存,因此我无法将此商品添加到SaleItem模型中,因为我不知道当前商品的ID。

Rails has accepts_nested_attributes_for and fields_for for this situation: Rails在这种情况下具有accepts_nested_attributes_forfields_for

# model
class Sale < ApplicationRecord
  has_many :sale_items
  accepts_nested_attributes_for :sale_items
end

but you'll also have to write client-side code that will modify your form (there was a gem for that - nested_form , but it is a bit outdated), so that it posts data in form of sale[sale_items_attributes][1][barcode]=12345 , sale[sale_items_attributes][2][barcode]=4321 , and modify controller to permit these through strong parameters ( params.require(:sale).permit(... , sale_items_attributes:[:id, :barcode]) ). 但是您还必须编写客户端代码来修改您的表单(有一个gem- nested_form ,但是有点过时了),以便它以sale[sale_items_attributes][1][barcode]=12345形式发布数据sale[sale_items_attributes][1][barcode]=12345sale[sale_items_attributes][2][barcode]=4321 ,并修改控制器以允许通过强参数( params.require(:sale).permit(... , sale_items_attributes:[:id, :barcode]) )。

Trick is that rails will save nested models together with parent one, also nothing will be saved if validation is not passed for any of the models. 诀窍是,rails将与父模型一起保存嵌套模型,如果未通过任何模型的验证,也将不保存任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM