2010-07-20 183 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