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. The Product's table columns are 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.
我对rails上的ruby很新...在我的_form.html.erb上我有一个collection_select字段,它是从名为Product的Model中填充的。产品的表格列是ID,名称和价格。一旦我从集合中选择了一个项目(产品),我想用所选产品的价格填充一个文本字段。
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
1 个解决方案
#1
0
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. There is no way to let onchange
run ruby code directly. All you can do is send an AJAX request in onchange
, and let your Rails application respond to that request.
所以onchange的内容只是一段javascript,可以在浏览器上运行。没有办法让onchange直接运行ruby代码。您所能做的就是在onchange中发送一个AJAX请求,让您的Rails应用程序响应该请求。
#1
0
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. There is no way to let onchange
run ruby code directly. All you can do is send an AJAX request in onchange
, and let your Rails application respond to that request.
所以onchange的内容只是一段javascript,可以在浏览器上运行。没有办法让onchange直接运行ruby代码。您所能做的就是在onchange中发送一个AJAX请求,让您的Rails应用程序响应该请求。