简体   繁体   中英

Set price value, whenever product is selected in rails

Rails newbie here. I am having issue with how to set default value for price.

Here's the code:

<%= simple_form_for(@order) do |f| %>
  <%= f.error_notification %>

  <%= f.input :customer_id, collection: Customer.all, %>
  <%= f.simple_fields_for :items do |i| %>
      <%= render 'item_fields', :f => i %>     
  <% end %>
    <%= link_to_add_association '+ product, f, :items %>

<% end %>

partial _item_fields form:

<%= f.input :qty %>
<%= f.select :product_id, Product.all.map { |p| [p.name, p.id }, { include_blank: true } %>
<%= f.text_field :price %>
<%= link_to_remove_association image_tag("delete.png") %>    

The plan is to set price value whenever product is selected so it can be saved. Was trying many ways with no luck.

Product table has name, price field.

I need your help to accomplish this. What is the best way to do that? Ajax, javascript?

Any help would be appreciated.

Basically, when you select a product_id, a price gets set, without something being sent to the server? You need JavaScript/JQuery for that.

The rule is when you want something changed in real time without a visit back to the server, you use JavaScript. Something like $('.product_id').on('change', function(){$('.price_field').value = $('.product_id').data('price')}) or something to that effect (a little rusty on the JQuery but I think things are manageable from here).

Product.all.collect { |p| [p.name, p.id, {'data-price'=>p.price}]} then you can access it through $('.product_id').data('price')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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