edgy
(edgy)
February 20, 2008, 9:00pm
1
Hi, I have one problem with validation
I am creating e-shop and I have products. This view look like this:
<% for product in @category.products %>
<div class="produktyBox">
<%= product.title %><br />
Price: <br />
<div style="color:red; font-size:large; font-weight:bold; margin-
bottom:5px"><%= number_with_delimiter(product.price, " ")%> Kč</
<%= link_to "Details", {:action => "product", :id =>
product.name_seo} %>
<% form_tag :action => "add_to_cart" do %>
<p>
<%= text_field_tag :quantity, "1", :size => 1 %>
<%= submit_tag "Buy" %>
</p>
<% end %>
</div>
<% end %>
In controller I need get value of text_field_tag (@value =
params[:quantity] )
Problem is with validation : ID "quantity" already defined
I need something like this <%= text_field_tag "quantity_"+product.id,
"1", :size => 1 %> .
This I get different name of text_field, but I don't know, How can I
get params to controller
Thank you
AndyV1
(AndyV)
February 21, 2008, 1:24pm
2
I'll go out on a limb and guess that you might have an object like
'LineItem' in your domain where:
class LineItem
belongs_to :order
has_one :product
...
end
LineItem has quantity and maybe discount_rate as attributes. With
that in mind:
<% @category.products.each do |product| %>
<div class="produktyBox">
<%= product.title %><br />
Price: <br />
<div style="color:red; font-size:large; font-weight:bold;
margin-
bottom:5px"><%= number_with_delimiter(product.price, " ")%> Kč</
<%= link_to "Details", {:action => "product", :id =>
product.name_seo} %>
<% form_for :line_item, LineItem.new(:product=>product), :url
=> url_for(:controller=>:order, :action=>:add_to_cart) do |f| %>
<%= f.hidden_field :product_id %>
<p>
<%= f.text_field :quantity, "1", :size => 1 %>
<%= submit_tag "Buy" %>
</p>
<% end %>
</div>
<% end %>
There are other improvements that you could make here, but the core of
what's going on is that you're wrapping the info going back to the
add_to_cart action in a line_item hash. The main change was using
form_for rather than form_tag so that you could wrap the product_id
(you'll need that, right?) along with the quantity in a line_item hash
(controller's perspective). To create an instance you'd:
item = LineItem.new( params[:line_item])
in your controller and it'd be loaded with both the quantity AND
product.
HTH,
AndyV
HTH,
AndyV