Trying to build a shopping cart based on the Agile Web Development 4th edition. The shopping cart is for selling t-shirts. The t-shirts have various size options, color options, and gender options. I want users to be able to select their options from lists, click “add to cart”, and have the matching t-shirt added to to the cart (in the form of a line_item).
I think I am SO close to getting this done. But not quite. Here are the relevant code snippets:
The Form (/_store.html.erb):
<div id="storefunctions">
<%= form_tag '/line_items/create', :id => "tshirt" do %>
<div>
size: <%= render 'size_select' %>
color: <%= render 'color_select' %>
gender: <%= render 'gender_select' %>
<%= hidden_field_tag(:message_content, @message.content) %></div
<div> <%= submit_tag 'add to cart' %></div>
<% end %>
Line_items Controller (/line_items/create.rb)
def create
@cart = current_cart
tshirt = Tshirt.where("size = ? AND gender = ? AND color = ?", params[:size], params[:gender], params[:color])
@line_item = @cart.line_items.build(:tshirt_id => tshirt.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to(@line_item.cart, :notice => 'Line item was successfully created.') }
format.xml { render :xml => @line_item, :status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors, :status => :unprocessable_entity }
end
end
end
When I click “add to cart” it says I have successfully added it to cart, but I can not access any information about the shirt. It says it is a nil.
Any help would be appreciated!
Model.where(...)is going to be an array of results, not a single result object, so you can’t call.idon it. You probably wantTshirt.where("size = ? AND gender = ? AND color = ?", params[:size], params[:gender], params[:color]).first