2010-09-11 23 views
0

我有一個精簡的購物車應用程序,目前有一個模型「購物車」,購物車ID存儲在一個會話。簡單的一個模型奇異的資源路由問題

車控制器有這種方法,所以我們始終有一個購物車

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

我的路線文件中有這樣一行

map.resource :cart 

我的購物車/顯示視圖看起來是這樣的,我加了形式,以便最終我可以更新項目的數量,但現在我只是編輯created_at屬性。

<% 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 %> 

最後,我更新的動作是這樣的:

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 

當我做出改變,以「created_at」屬性中的「顯示」頁面上,該屬性被成功更新,但是當我重定向,我得到一個bizare URL這樣

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

我已經擺弄更新操作,並能得到整個事情做這個

很好地工作
# 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 

它與respond_to塊有關,導致它搞砸了,我真的很感激任何幫助,我可以得到這一點。

謝謝

回答

1

對於奇異資源,您不需要在路徑中指定對象。

所以,你應該這樣做:

<%= link_to 'Edit', edit_cart_path %> 

=====修訂=====

我剛剛找到你真正的問題^^」(但原本應該是真的太)

您使用form_for(@cart) do |f|,這產生了醜陋的路徑

請改爲form_for(@cart, :url => cart_path) do |f|

我不知道爲什麼,但它應該沒問題......

+0

這不是我真正想做的。 – dangerousdave 2010-09-11 17:51:10

+0

請在購物車/顯示視圖文件中檢查表單的動作網址,看看它是否有點奇怪... – PeterWong 2010-09-11 18:18:35

+0

這樣做很有效!但爲什麼不默認的form_for(@cart)工作?我不明白。 – dangerousdave 2010-09-11 18:18:53