Search code examples
ruby-on-railsbarcode

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.


Solution

  • Rails has accepts_nested_attributes_for and fields_for for this situation:

    # 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])).

    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.