2010-07-20 180 views
2

我想創建一個機制讓用戶跟蹤其他最喜歡的用戶,類似於SO最喜歡的問題。我正在使用Rails 3.0測試版。Rails3嵌套路由問題

要做到這一點,我有一個用戶喜歡的HABTM關係,預計其工作原理:

class User < ActiveRecord::Base 
    has_and_belongs_to_many :favorites, :class_name => "User", :join_table => "favorites", :association_foreign_key => "favorite_id", :foreign_key => "user_id" 
end 

的收藏控制器只需要的7種REST風格的方法3來管理用戶的收藏夾:

class FavoritesController < ApplicationController 

    # GET /favorites 
    # GET /favorites.xml 
    def index 

    @user = User.find(params[:user_id]) 
    @favorites = @user.favorites.joins(:profile).order("last_name,first_name") 

    ... 

    end 

    def create 

    @favorite = User.find(params[:id]) 
    current_user.favorites << @favorite 

    ... 

    end 

    def destroy 

    @favorite = User.find(params[:id]) 
    current_user.favorites.delete(@favorite) 

    ... 

    end 

end 

的routes.rb中文件包含路由指令:

resources :users, :except => :destroy do 
    resources :favorites, :only => [:index,:create,:destroy] 
end 

該基因利率這些用戶喜歡的路線:

GET /users/:user_id/favorites(.:format)   {:controller=>"favorites", :action=>"index"} 
user_favorites POST /users/:user_id/favorites(.:format)   {:controller=>"favorites", :action=>"create"} 
user_favorite DELETE /users/:user_id/favorites/:id(.:format)  {:controller=>"favorites", :action=>"destroy"} 

在用戶的顯示視圖,用戶(@user)可切換爲使用圖片鏈接的最愛,因爲預期其工作原理:

<% if [test if user is a favorite] %> 

    # http://localhost:3000/favorites/destroy/:id?post=true 
    <%= link_to image_tag("favorite.png", :border => 0), :controller => :favorites, :action => :destroy, :post=>true, :id => @user %> 

<% else %> 

    # http://localhost:3000/favorites/create/:id?post=true 
    <%= link_to image_tag("not-favorite.png", :border => 0), :controller => :favorites, :action => :create, :post=>true, :id => @user %> 

<% end %> 

然而,在CURRENT_USER的喜愛索引視圖中,每個的link_to用戶喜愛:

# http://localhost:3010/users/4/favorites/3?post=true 
<%= link_to image_tag("favorite.png", :border => 0), :controller => :favorites, :action => :destroy, :id => favorite, :post=>true %> 

生成一條錯誤:

沒有路由匹配 「/用戶/ 4 /收藏/ 3」

問題:

  1. 我是否正確指定我的路由?看起來創建和銷燬路由只需要最喜歡的ID,因爲收藏夾的「所有者」始終是current_user。
  2. 如果我只是在Show視圖中引用Controller/Action,我是否還需要創建/銷燬路由?
  3. 爲什麼Index View中的link_to不能正常工作?
  4. 對整體方法有什麼改進嗎?

回答

3

你的路由看起來很好。

雖然我認爲你的link_to有問題。首先,RESTful方式不是使用:controller和:action參數來指定URL。正確的方法是使用生成的URL方法,例如user_favorite_path。另外,您需要在定位銷燬操作時指定:method參數。這是我認爲的link_to應該是這樣的:

<%= link_to image_tag("favorite.png", :border => 0), user_favorite_path(@user, @favorite), :method => :delete %>

我相信它說沒有路由的原因匹配的網址是因爲你沒有指定:方法:刪除。

+0

需要成爲: <%= link_to image_tag(「favorite」。png「,:border => 0),user_favorite_path(current_user,@ user),:method =>:delete%> 謝謝! – craig 2010-07-20 15:02:57

0

在你的rake路由輸出中,參數需要的是:user_id不是:id,所以你需要在你的link_to調用中發送。

+0

已更改索引查看:user_id =>收藏夾。 URL變爲http:// localhost:3010/favorites/destroy?post = true&user_id = 3。新錯誤:無法找到沒有ID的用戶 – craig 2010-07-20 14:21:55