0

这是在我的 routes.rb 文件中:

  resources :users, :only => [:create] do
    get 'search'
    member do
      get 'images'
      get 'followers'
      get 'following'

      post 'follow'
      delete 'follow'
    end
  end

但我也希望有人能够调用/self/feed 和/self/comments(其中comment 是一种资源),并且self 指的是会话中的id。我怎样才能做到这一点而不重复自己?

谢谢

4

1 回答 1

0

如果 id 已经在会话中,那么您不需要将它作为 URL 参数传递。考虑传递会话 id 的危险:如果传递了不是会话 id 的 id 会发生什么?你会怎么处理?

对于您的评论路线,您应该考虑这样的事情:

# config/routes.rb
resources :comments

然后,在评论控制器中,您将查询 id 为会话的所有评论:

# app/controllers/comments_controller.rb
def index
    @comments = User.find(session[:id]).comments // assuming that the session `id` variable is the identifier for a `User` model
end

因此,访问会话评论所需要做的就是访问/comments路径。

编辑:

要通过别名路径访问会话的用户评论/self/comments,您可以创建一个命名匹配路由:

# config/routes.rb    
match 'self/comments' => 'user#self_comments'

然后,您将在comments_controller.rbfor中添加一个操作self_comments。您大概可以重用您的评论index.html.erb模板来呈现结果:

# app/controllers/comments_controller.rb
def self_comments
    @comments = User.find(session[:id]).comments
    render :template => 'comments/index'
end
于 2013-06-15T22:19:21.967 回答