我想创建一个机制让用户跟踪其他最喜欢的用户,类似于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”
问题:
- 我是否正确指定我的路由?看起来创建和销毁路由只需要最喜欢的ID,因为收藏夹的“所有者”始终是current_user。
- 如果我只是在Show视图中引用Controller/Action,我是否还需要创建/销毁路由?
- 为什么Index View中的link_to不能正常工作?
- 对整体方法有什么改进吗?
需要成为: <%= link_to image_tag(“favorite”。png“,:border => 0),user_favorite_path(current_user,@ user),:method =>:delete%> 谢谢! – craig 2010-07-20 15:02:57