简体   繁体   English

触发:onchange事件时(红宝石在Rails 4上),如何调用ruby方法?

[英]How to call a ruby method when :onchange event is triggered (ruby on rails 4)?

I am pretty new to ruby on rails... On my _form.html.erb I have a collection_select field, which is populated from a Model called Product. 我是红宝石的_form.html.erb ...在_form.html.erb我有一个collection_select字段,该字段是从名为Product的模型中填充的。 The Product's table columns are id, name, and price . 产品的表格列是id, name, and price Once I select an item (product) from the collection I would like to populate a text field with the price of the selected product. 从集合中选择商品后,我想在文本字段中填充所选商品的价格。

So far I have the following code IOT trigger an event when selecting an item: 到目前为止,我有以下代码IOT在选择项目时触发事件:

<%= collection_select( :warehouse, :product_id, Product.all, :id, :name, {}, {:onchange => "alert('Hello World');"} )%>

How can I call a ruby method which would let me populate the text_field with the corresponding price for the selected product? 如何调用ruby方法,该方法将使我使用选定产品的相应价格填充text_field?

For the method I was thinking something like... 对于方法,我在想类似...

def set_price
      @price = Product.find(params[:id]).price
end

The erb snippet erb代码段

<%= collection_select( :warehouse, :product_id, Product.all, :id, :name, {}, {:onchange => "alert('Hello World');"} )%>

generates the html snippet like this 生成这样的html代码段

<select name="warehouse[product_id]" onchange="alert('Hello World');">
  <option value="1">Product 1</option>
  <option value="2">Product 2</option>
  ...
</select>

So the content of onchange is just a piece of javascript, which runs on browsers. 因此onchange的内容只是一段JavaScript,可在浏览器上运行。 There is no way to let onchange run ruby code directly. 没有办法让onchange直接运行ruby代码。 All you can do is send an AJAX request in onchange , and let your Rails application respond to that request. 您所能做的就是在onchange发送一个AJAX请求,并让您的Rails应用程序响应该请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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