问题描述:

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')

相关阅读:
Top