title: How to complete form fields automatically in Ruby On Rails
body: <p>Regards! I am creating an inventory system in which, at the time of making the sale, I need to write the code or product name, I need to get the price out of it, without the need to write it manually, however,  I have little knowledge of javascript, I have found several resources like autocomplete of jquery, however, I can not do it, I followed the tutorial of RailsCasts about dynamic selectors, nevertheless I need this to be achieved with text fields, I appreciate immensely someone can help me, specifically in the output model, I have the items in the output_item model, and my product model:</p>
  
  <p><strong>output_form.html.erb</strong></p>
  
  <pre><code>&lt;%= form_with(model: output, local: true, id: "form") do |f| %&gt;
  
            &lt;div class="form-group"&gt;
              &lt;%= f.label :invoice %&gt; &lt;br&gt;
              &lt;%= f.text_field :invoice, class: "form-control", placeholder: "CE0001" %&gt;
            &lt;/div&gt;      
  
            &lt;div class="form-group"&gt;
              &lt;%= f.label :customer %&gt; &lt;br&gt;
              &lt;%= f.text_field :customer, class: "form-control", placeholder: "Ej. Jeovanny" %&gt;
            &lt;/div&gt;
  
            &lt;table width="100%" id="output-item"&gt;
              &lt;thead&gt;
                &lt;th&gt;Product&lt;/th&gt;
                &lt;th&gt;Quantity&lt;/th&gt;
                &lt;th&gt;Price&lt;/th&gt;
                &lt;th&gt;Total&lt;/th&gt;
                &lt;th&gt;Options&lt;/th&gt;
              &lt;/thead&gt;
              &lt;tbody&gt;
                &lt;%= f.fields_for :output_items, id: "form" do |item| %&gt;
                  &lt;%= render "output_item_fields", f: item %&gt;
                &lt;% end %&gt;
              &lt;/tbody&gt;
            &lt;/table&gt;
  
            &lt;div class="form-group mb-0"&gt;
              &lt;%= link_to_add_association 'Add product', f, :output_items, :"data-association-insertion-node" =&gt; "table#output-item",:"data-association-insertion-method" =&gt; "append", class: "btn btn-success" %&gt;        
            &lt;/div&gt;      
  
        &lt;div class="form-group&gt;
            &lt;%= link_to "Cancelar", outputs_path, class: "btn btn-danger" %&gt;        
            &lt;%= f.submit "Send", class: "btn btn-primary" %&gt;  
        &lt;/div&gt;        
  
  &lt;% end %&gt;
  </code></pre>
  
  <p><strong>output_items_fields.html.erb</strong></p>
  
  <pre><code>&lt;tr class="item"&gt;
      &lt;td&gt;&lt;%= f.text_field :product_id, class: "form-control field" %&gt;&lt;/td&gt;
      &lt;td&gt;&lt;%= f.text_field :quantity, class: "form-control field quantity" %&gt;&lt;/td&gt;
      &lt;td&gt;&lt;%= f.text_field :price, class: "form-control field price" %&gt;&lt;/td&gt;
      &lt;td&gt;&lt;input type="text" class="form-control field subtotal"&gt;&lt;/td&gt;
      &lt;td class="text-center"&gt;
          &lt;%= link_to_remove_association f, { wrapper_class: "item", class: "btn btn-danger" } do %&gt;
              &lt;i class="fal fa-trash-alt"&gt;&lt;/i&gt;
          &lt;% end %&gt;
      &lt;/td&gt;
  &lt;/tr&gt;
  </code></pre>
  
  <p><strong>product.rb</strong></p>
  
  <pre><code>class Product &lt; ApplicationRecord
  
      has_many :input_items
      has_many :output_items
      validates :code, :name, presence: true
  
      def purchase
          input_items.pluck(:quantity).sum
      end
  
      def sale
          output_items.pluck(:quantity).sum
      end
  
      def stock
          (input_items.pluck(:quantity).sum - output_items.pluck(:quantity).sum)
      end
  
      def price
          self.input_items.sum(:price) / self.input_items.count
      end
  
  end
  </code></pre>
  
  <p><strong>Output.rb</strong></p>
  
  <pre><code>class Output &lt; ApplicationRecord
  
      has_many :output_items, inverse_of: :output, :dependent =&gt; :delete_all
      accepts_nested_attributes_for :output_items, reject_if: :all_blank, allow_destroy: true    
  
      validates :invoice, :provider, presence: true
  
  end
  </code></pre>
  
  <p><strong>output_item.rb</strong></p>
  
  <pre><code>class OutputItem &lt; ApplicationRecord
  
      belongs_to :product
      belongs_to :output
      validates :quantity, :price, numericality: true, presence: true  
  
  end
  
  class Product &lt; ApplicationRecord
  
      has_many :output_items
  
  end
  </code></pre>
  
  <p><strong>input.rb</strong></p>
  
  <pre><code>class Input &lt; ApplicationRecord
  
      has_many :input_items, inverse_of: :input, :dependent =&gt; :delete_all
      accepts_nested_attributes_for :input_items, reject_if: :all_blank, allow_destroy: true    
  
      validates :invoice, :provider, presence: true
  
  end
  </code></pre>
  
  <p><strong>input_item.rb</strong></p>
  
  <pre><code>class InputItem &lt; ApplicationRecord
  
    belongs_to :product
    belongs_to :input
    validates :quantity, :price, numericality: true, presence: true
  
  end
  </code></pre>
  
  <p><strong>input_migrate.rb</strong></p>
  
  <pre><code>class CreateInputs &lt; ActiveRecord::Migration[5.2]
    def change
      create_table :inputs do |t|
        t.string :invoice
        t.string :provider
  
        t.timestamps
      end
    end
  end
  </code></pre>
  
  <p><strong>input_items_migration.rb</strong></p>
  
  <pre><code>class CreateInputItems &lt; ActiveRecord::Migration[5.2]
    def change
      create_table :input_items do |t|
        t.integer :product_id
        t.float :quantity
        t.float :price
        t.belongs_to :input, foreign_key: true
  
        t.timestamps
      end
    end
  end
  </code></pre>
  
  <p><strong>product_migrate.rb</strong></p>
  
  <pre><code>class CreateProducts &lt; ActiveRecord::Migration[5.2]
    def change
      create_table :products do |t|
        t.string :code
        t.string :name
        t.float :utility
  
        t.timestamps
      end
    end
  end
  </code></pre>
  
  <p><strong>output_migrate.rb</strong></p>
  
  <pre><code>class CreateOutputs &lt; ActiveRecord::Migration[5.2]
    def change
      create_table :outputs do |t|
        t.string :invoice
        t.string :customer
  
        t.timestamps
      end
    end
  end
  </code></pre>
  
  <p><strong>output_item_migrate.rb</strong>    </p>
  
  <pre><code>class CreateOutputItems &lt; ActiveRecord::Migration[5.2]
    def change
      create_table :output_items do |t|
        t.integer :product_id
        t.float :quantity
        t.float :price
        t.belongs_to :output, foreign_key: true
  
        t.timestamps
      end
    end
  end
  </code></pre>
  
  <p>The code that RailsCast offers, to autocomplete selectors is with:</p>
  
  <pre><code>(function() {
      jQuery(function() {
        var states;
        $('#input_price').parent().hide();
        states = $('#input_price').html();
        return $('#input_product_id').change(function() {
          var country, escaped_country, options;
          country = $('#input_product_id :selected').text();
          escaped_country = country.replace(/([ #;&amp;,.+*~\':"!^$[\]()=&gt;|\/@])/g, '\\$1');
          options = $(states).filter("optgroup[label='" + escaped_country + "']").html();
          if (options) {
            $('#input_price').html(options);
            return $('#input_price').parent().show();
          } else {
            $('#input_price').empty();
            return $('#input_price').parent().hide();
          }
        });
      });
  
    }).call(this); 
  </code></pre>
  
  <p>In what way could adapt, or what is the most convenient way to do this, as an added data, I use cocoon for dynamic items, I appreciate immensely, can help me, Regards!</p>
  
  <hr>
  
  <p><strong>Updates</strong></p>
  
  <p><strong>output_items_fields.html.erb</strong></p>
  
  <pre><code>&lt;tr class="item"&gt;
      &lt;td&gt;&lt;%= f.text_field :product_id, class: "form-control field" %&gt;&lt;/td&gt;
      &lt;td&gt;&lt;%= f.text_field :quantity, class: "form-control field quantity" %&gt;&lt;/td&gt;
      &lt;td&gt;&lt;%= f.text_field :price, class: "form-control field price" %&gt;&lt;/td&gt;
      &lt;td&gt;&lt;input type="text" class="form-control field subtotal"&gt;&lt;/td&gt;
      &lt;td class="text-center"&gt;
          &lt;%= link_to_remove_association f, { wrapper_class: "item", class: "btn btn-danger" } do %&gt;
              &lt;i class="fal fa-trash-alt"&gt;&lt;/i&gt;
          &lt;% end %&gt;
      &lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;% content_for :javascript do %&gt; 
    &lt;script type="text/javascript"&gt;var product_info = $.parseJSON('&lt;%= @product_info.to_json.html_safe %&gt;');&lt;/script&gt;
  &lt;% end %&gt;
  
  &lt;% content_for :javascript do %&gt; 
      &lt;script type="text/javascript"&gt;
        var product_info = $.parseJSON('&lt;%= @product_info.to_json.html_safe %&gt;');
        (function() {
            jQuery(function() {
              var product = product_info[$('#output_product_id')]
              return $('#output_product_id').change(function() {
              if (product) {                     
                $('#output_price').val(product.price);
                $('#output_description').val(product.description);
              } else {
                $('#output_price').val("");
                }
              });
            });
          }).call(this); 
      &lt;/script&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p><strong>outputs_controller.rb</strong></p>
  
  <pre><code>class OutputsController &lt; ApplicationController
    before_action :set_output, only: [:show, :edit, :update, :destroy]
  
    def new
      @output = Output.new
      @output.output_items.build
      @product_info = Product.joins(:input_items).select(:price).all.inject({}) {|a, b| a[b.input_items] = {price: b.price}}  
    end
  end
  </code></pre>
  
  <p>When I look for the product_info and testing in the browser console, I get it:</p>
  
  <pre><code>console.log(product_info)
  Object { price: null }
  debugger eval code:1:1
  undefined
  
  console.log('testing')
  testing debugger eval code:1:1
  undefined
  </code></pre>