views:

30

answers:

1

I have a stripped down shopping cart application, currently with one model "cart", the cart id is stored in a session.

the cart controller has this method so we always have a cart

  def initialize_cart
    if session[:cart_id]
      @cart = Cart.find(session[:cart_id])
    else
      @cart = Cart.create
      session[:cart_id] = @cart.id
    end
  end

my routes file has this one line

  map.resource :cart

my cart/show view looks like this, i have added a form to it so that ultimately i can update the quantity of items, but for now i am just editing the created_at attribute.

<% form_for(@cart) do |f| %>
  <%= f.date_select :created_at %>

  <p>
    <%= f.submit 'Update' %>
  </p>
<% end %>


<%= link_to 'Edit', edit_cart_path(@cart) %> |
<%= link_to 'Back', cart_path %>

and finally, my update action looks like this:

  def update
    #@cart = Cart.find(params[:id])

    respond_to do |format|
      if @cart.update_attributes(params[:cart])
        format.html { redirect_to(cart_path) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @cart.errors, :status => :unprocessable_entity }
      end
    end
  end

when i make a change to "created_at" attribute on the "show" page, the attribute is successfully updated, but when i get redirected, i get a bizare url like this

http://192.168.0.10:3000/cart.%23%3Ccart:0x23d46fc%3E

I have fiddled with the update action, and can get the whole thing to work perfectly by doing this

  # PUT /carts/1
  # PUT /carts/1.xml
  def update
    #@cart = Cart.find(params[:id])

    #respond_to do |format|
      if @cart.update_attributes(params[:cart])
         redirect_to(cart_path) 
        # head :ok 
      #else
        # render :action => "edit" 
        # render :xml => @cart.errors, :status => :unprocessable_entity }
      end
    #end

Its something to do with the respond_to block that is causing it to mess up, i would really appreciate any help i can get with this.

Thanks

+1  A: 

For singular resource, you don't need to specify the object in the routes.

So you should use this:

<%= link_to 'Edit', edit_cart_path %>

===== UPDATED =====

I just found your real problem ^^" (but the original should be true too)

You used form_for(@cart) do |f|, which produced that ugly path

Please change to form_for(@cart, :url => cart_path) do |f|

I don't know why too, but it should be ok......

PeterWong
That not really what i am trying to do.
Jon
Please check your form's action url in the cart/show view file to see if it is strange...
PeterWong
That works! but why doesn't the default form_for(@cart) work??? i don't understand.
Jon
It seems that rails' form_for recognized resources only, but not resource.
PeterWong