我在表格中有这个
<%= simpleform_for @customer_bill do |f| %>
<%= f.label :product_id %>
<%= f.collection_select :product_id,Product.all,:id,:title, :prompt => "Select a Product", :style => 'width:150px;' %>
<%= f.label :price %>
<%= f.text_field :price, :size=>20, :id =>"price", :class =>"price" %>
<br/>
/*rest of code*/
在产品表中,我有“产品标题”和“价格”。我在客户账单和产品模型之间建立了必要的关联。
一旦选择产品,价格就会自动出现。最好的方法是什么? Ajax/Jquery 我怎样才能继续解决这个问题???任何指导都会有所帮助。
最佳答案
您可以使用 select-tag 的 data-xxx 属性来存储价格并让 javascript 处理它:
JavaScript:
$(function() {
$('#products').change(function() {
var product_id = $(this).val()
var price = eval($(this).data('prices'))[product_id]
$("#price").html(price)
})
})
模板(这是 Haml,但我想即使您是 ERb 人员,您也会明白这个想法):
= simple_form_for ........ do |f|
- prices = Hash[Product.all.map{|p| [p.id, p.price]}].to_json
= f.association :product, input_html: {data:{prices: prices}, id: 'products'}
= f.label :price, id: 'price'
请注意使用f.association
而不是f.collection_select
。我认为在你的情况下它使用起来更简单。
关于ruby-on-rails - 在 ruby on Rails 中选择产品后动态选择价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10698047/