I need to do a specific form with a parameter that is not associated to the Model that im using. See, i have in my controller (and i can reference them in my view) a specific "Order" and an array of "Products".
#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
In my view i need to render a list with all the products with their attributes (name, description, price), a small number field next to each product and a link to "Add" the product.
I can do the table to show every attribute in each individual product of my products array, problem is, i dont know how to create a number field next to each row in my table and a link to the "Add" action, which is just a point in my API, mydomain.com/add/product/:id_order/:id_product/:amount (alias as add_product_order )
:id_order correspond to the id of the order, which i have (@order.id)
:id_product correspond to the id of the specific product of the row, which i have (product.id)
:amount must be the amount specified by the user, but i have no idea how to reference it inside the view.
The rails helper form_for, form_tag etc ... requires the url to send the data however i cant use add_product_order_path because i would need the :amount parameter so it gives me an error (but if i use a constant amount like 1, it works).
In conclusion:
<% @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 %>
What would need to be in the ??? to send the value of the amount field to the add_product_order_path?
So, the amount value its an input with an unknown value. I highly recommend that use some JS to achieve this. Something like:
$('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);
});
I hope it helps.
UPDATE
Sorry, did'nt saw that you're using method: :post
, this generates a hidden form, you have to change the hidden input value. Its posible with javascript too:
$('table td a').on('click', function(e) {
var amountVal = $(this).parent('tr').find('input').val();
$(this).parent().find('input[name*="amount"]').val(amountVal);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.