Привет! Я создаю систему инвентаризации, в которой во время совершения продажи мне нужно написать код или название продукта, мне нужно получить цену, без необходимости писать это вручную, однако у меня мало Знание javascript, я нашел несколько ресурсов, таких как автозаполнение jquery, однако, я не могу этого сделать, я следовал учебнику RailsCasts по динамическим селекторам, тем не менее мне нужно, чтобы это было достигнуто с помощью текстовых полей, я очень ценю, что кто-то может мне помочь В частности, в выходной модели у меня есть элементы в модели output_item и модель моего продукта:
output_form.html.erb
<%= form_with(model: output, local: true, id: "form") do |f| %>
<div class="form-group">
<%= f.label :invoice %> <br>
<%= f.text_field :invoice, class: "form-control", placeholder: "CE0001" %>
</div>
<div class="form-group">
<%= f.label :customer %> <br>
<%= f.text_field :customer, class: "form-control", placeholder: "Ej. Jeovanny" %>
</div>
<table width="100%" id="output-item">
<thead>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Options</th>
</thead>
<tbody>
<%= f.fields_for :output_items, id: "form" do |item| %>
<%= render "output_item_fields", f: item %>
<% end %>
</tbody>
</table>
<div class="form-group mb-0">
<%= link_to_add_association 'Add product', f, :output_items, :"data-association-insertion-node" => "table#output-item",:"data-association-insertion-method" => "append", class: "btn btn-success" %>
</div>
<div class="form-group>
<%= link_to "Cancelar", outputs_path, class: "btn btn-danger" %>
<%= f.submit "Send", class: "btn btn-primary" %>
</div>
<% end %>
output_items_fields.html.erb
<tr class="item">
<td><%= f.text_field :product_id, class: "form-control field" %></td>
<td><%= f.text_field :quantity, class: "form-control field quantity" %></td>
<td><%= f.text_field :price, class: "form-control field price" %></td>
<td><input type="text" class="form-control field subtotal"></td>
<td class="text-center">
<%= link_to_remove_association f, { wrapper_class: "item", class: "btn btn-danger" } do %>
<i class="fal fa-trash-alt"></i>
<% end %>
</td>
</tr>
product.rb
class Product < 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
Output.rb
class Output < ApplicationRecord
has_many :output_items, inverse_of: :output, :dependent => :delete_all
accepts_nested_attributes_for :output_items, reject_if: :all_blank, allow_destroy: true
validates :invoice, :provider, presence: true
end
output_item.rb
class OutputItem < ApplicationRecord
belongs_to :product
belongs_to :output
validates :quantity, :price, numericality: true, presence: true
end
class Product < ApplicationRecord
has_many :output_items
end
input.rb
class Input < ApplicationRecord
has_many :input_items, inverse_of: :input, :dependent => :delete_all
accepts_nested_attributes_for :input_items, reject_if: :all_blank, allow_destroy: true
validates :invoice, :provider, presence: true
end
input_item.rb
class InputItem < ApplicationRecord
belongs_to :product
belongs_to :input
validates :quantity, :price, numericality: true, presence: true
end
input_migrate.rb
class CreateInputs < ActiveRecord::Migration[5.2]
def change
create_table :inputs do |t|
t.string :invoice
t.string :provider
t.timestamps
end
end
end
input_items_migration.rb
class CreateInputItems < 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
product_migrate.rb
class CreateProducts < 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
output_migrate.rb
class CreateOutputs < ActiveRecord::Migration[5.2]
def change
create_table :outputs do |t|
t.string :invoice
t.string :customer
t.timestamps
end
end
end
output_item_migrate.rb
class CreateOutputItems < 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
Код, который предлагает RailsCast для автозаполнения селекторов:
(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(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/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);
Каким образом можно было бы адаптироваться, или какой самый удобный способ сделать это, в качестве дополнительных данных я использую кокон для динамических предметов, я очень благодарен, могу помочь мне, С уважением!
Обновление
output_items_fields.html.erb
<tr class="item">
<td><%= f.text_field :product_id, class: "form-control field" %></td>
<td><%= f.text_field :quantity, class: "form-control field quantity" %></td>
<td><%= f.text_field :price, class: "form-control field price" %></td>
<td><input type="text" class="form-control field subtotal"></td>
<td class="text-center">
<%= link_to_remove_association f, { wrapper_class: "item", class: "btn btn-danger" } do %>
<i class="fal fa-trash-alt"></i>
<% end %>
</td>
</tr>
<% content_for :javascript do %>
<script type="text/javascript">var product_info = $.parseJSON('<%= @product_info.to_json.html_safe %>');</script>
<% end %>
<% content_for :javascript do %>
<script type="text/javascript">
var product_info = $.parseJSON('<%= @product_info.to_json.html_safe %>');
(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);
</script>
<% end %>
outputs_controller.rb
class OutputsController < 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
Когда я смотрю на product_info и тестирую в консоли браузера, я получаю:
console.log(product_info)
Object { price: null }
debugger eval code:1:1
undefined
console.log('testing')
testing debugger eval code:1:1
undefined