Ruby on rails 3 动态场,场为

Ruby on rails 3 动态场,场为,ruby-on-rails-3,fields-for,Ruby On Rails 3,Fields For,我有一个“销售”表格,我使用字段来输入有关要销售的产品的信息 以下是我的表单字段: <%= f.fields_for :sellproducts do |c| %> <%= c.label :product %> <%= c.grouped_collection_select :product_id, Category.order(:name), :products, :name, :id, :name, :include_blank => true

我有一个“销售”表格,我使用字段来输入有关要销售的产品的信息

以下是我的表单字段:

<%= f.fields_for :sellproducts do |c| %>
    <%= c.label :product %> <%= c.grouped_collection_select :product_id, Category.order(:name), :products, :name, :id, :name, :include_blank => true  %>
    <%= c.label :quantity %> <%= c.text_field :quantity, :size =>"5" %><br />

    <%= c.label :cost %> <%= c.text_field :cost, :size =>"5" %>

    <%= c.link_to_remove "Delete" %>

<% end %>

正确%>
“5”%>
"5" %>
当用户在选择字段中选择产品时,我希望“成本”文本_字段动态填充product.price的值,但我不知道如何执行此操作。事实上,我不知道如何得到值,然后把它

有人能帮我吗


非常感谢。

我想有两种方法可以做到这一点,都涉及JS

非Ajax: 构建您的选项,并包括每个产品的数据属性

<option value="<%= product.id %>" data-price="<%= product.price %>"><%= product.name %></option>
优点:有数据 缺点:您必须管理表单帮助程序附带的“选定”部分

Ajax(更好的方式): 添加检索所选产品价格的onchange事件

$('body').on('change', 'select.products', function(){
    var that = $(this),
      , costInput = that.parent("fieldset").("input.cost"); # Perhaps if you wrap the elements in a fieldset

     $.ajax({
        url: "products/price",
        data: {id: that.find('option:selected').val()),
        dataType: 'script'
    }).done(function ( price ) {
        costInput.val(price)
    });
});
优点:无需对html大惊小怪
缺点:想不出有什么值得注意的。

从表格中扣除费用听起来是个非常糟糕的主意。另一方面,向客户展示可能有用,但最好不要使用输入。事实上,它只是用来获取信息,不是为客户,而是为卖家。如果下面的答案解决了您的问题,请告诉我。
$('body').on('change', 'select.products', function(){
    var that = $(this),
      , costInput = that.parent("fieldset").("input.cost"); # Perhaps if you wrap the elements in a fieldset

     $.ajax({
        url: "products/price",
        data: {id: that.find('option:selected').val()),
        dataType: 'script'
    }).done(function ( price ) {
        costInput.val(price)
    });
});