繁体   English   中英

Ruby on Rails,将自定义参数引用到表单中的特定URL

[英]Ruby on Rails, reference custom parameter inside form to specific url

我需要使用不与即时通讯所使用的模型相关联的参数来做特定形式。 看,我在控制器中有一个(可以在我的视图中引用它们)一个特定的“订单”和一个“产品”数组。

#this controller responds to mydomain.com/new/order/:id_order
class MyController < ApplicationController
...
  def my_page
    @order = Order.find(params[:id_order])
    @products = Product.all
  end
...
end

在我看来,我需要绘制一个列表,其中包含所有产品及其属性(名称,描述,价格),每个产品旁边的小字段以及指向“添加”产品的链接。

我可以做一个表来显示我的产品数组的每个单独产品中的每个属性,问题是,我不知道如何在我的表中的每一行旁边创建一个数字字段以及一个指向“添加”操作的链接,这仅仅是我的API中的一点mydomain.com/add/product/:id_order/:id_product/:amount (别名为add_product_order

:id_order对应于我拥有的订单ID(@ order.id)
:id_product对应于行中特定产品的ID,我拥有(product.id)
:amount必须是用户指定的数量,但是我不知道如何在视图中引用它。

Rails的帮助器form_for,form_tag等...需要url发送数据,但是我不能使用add_product_order_path,因为我需要:amount参数,所以会给我一个错误(但是如果我使用1等常量,就可以了) 。

结论:

<% @products.each do |product| %>
      <tr>
          <td><%= product.name %></td>
          <td><%= product.description %></td>
          <td><%= product.price %></td>
          <td><input type="number" name="amount" min="1"></td>
          <td><%= link_to 'Add', add_product_order_path(id_order: @order.id, id_product: product.id, amount: *???* ), method: :post %></td>
      </tr>
<% end %>

???中需要什么 将金额字段的值发送到add_product_order_path?

因此,金额值是一个未知值的输入。 我强烈建议使用一些JS来实现。 就像是:

$('table td a').on('click', function(e) {
   var amountVal = $(this).parent('tr').find('input').val();
   var newUrl = location.href.replace("amount=", "amount="+amountVal);
   $(this).attr('href', newUrl);
});

希望对您有所帮助。

UPDATE

抱歉,没有看到您正在使用method: :post ,这会生成隐藏的表单,您必须更改隐藏的输入值。 它也可以和javascript一起使用:

$('table td a').on('click', function(e) {
   var amountVal = $(this).parent('tr').find('input').val();
   $(this).parent().find('input[name*="amount"]').val(amountVal);
});

暂无
暂无

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

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