rails / jquery如何在js.erb文件中将数据从jquery传递到嵌入式ruby?

时间:2018-03-27 20:55:36

标签: jquery ruby-on-rails

在我看来,我有一个选择框从ProductPrice模型(has_many关系)拉出产品定价。

我试图从ProuductPrice模型中获取价格,以使用所选选项的价格更新视图中的范围。

view:

<label>Size</label>
<select id="volumeinfo" name="volumeinfo">
  <%= options_from_collection_for_select(@product.prices, :id, :volume_info) %>
</select>

<span id="price"></price>



product_prices model

def volume_info
  "#{volume} #{unit}"
end



volumeinfo.js.erb

productid = $( "#volumeinfo" ).val()

$( "#volumeinfo" ).change(function() {
  // Possible to fetch productid from ProductPrice model?
  $("#price").text("<%= ProductPrice.find().price %>")
});

1 个答案:

答案 0 :(得分:0)

您可以使用类似的内容将data-price属性添加到您的选项中:

options_for_select(@product.map{ |product| [product.name, product.id, { 'data-price' => product.price }] })

然后使用jquery从所选选项中获取data-price属性的值,如下所示:

$("#volumeinfo").find("option:selected").attr("data-price)

使用此方法,您无需进行任何不必要的ajax请求即可获得价格。