如果 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.rb
for中添加一个操作self_comments
。您大概可以重用您的评论index.html.erb
模板来呈现结果:
# app/controllers/comments_controller.rb
def self_comments
@comments = User.find(session[:id]).comments
render :template => 'comments/index'
end