关于只有 rails 中的资源的嵌套资源
About nested resources with just resources in rails
问题是我想让嵌套资源和普通资源在控制器中指向相同的动作,但根据嵌套资源是否可用而采取不同的行动。
Routes.rb
resources :users do
resources :comments //For having nested routes
end
resources :comments //For having normal routes
嵌套资源
例如
Class CommentsController < ApplicationController
def index
@user = User.find(params[:id])
@comment = @user.comments.find(params[:id])
end
现在,
如果我只想查找所有评论,我想使用
/comments
否则,如果我在用户页面中点击我得到的所有评论
/user/:user_id/comments
因此,如何配置以确保生成正确的页面。
如果我是你,我会这样做:
def index
@comment = Comment.find_by(user_id: params[:user_id], id: params[:id])
# It looked weird that you tried to find a @comment
# instead of @comments in action `index`
# I think you made a typing mistake and this can be help
@comments = Comment.where(user_id: params[:user_id])
end
问题是我想让嵌套资源和普通资源在控制器中指向相同的动作,但根据嵌套资源是否可用而采取不同的行动。
Routes.rb
resources :users do
resources :comments //For having nested routes
end
resources :comments //For having normal routes
嵌套资源
例如
Class CommentsController < ApplicationController
def index
@user = User.find(params[:id])
@comment = @user.comments.find(params[:id])
end
现在,
如果我只想查找所有评论,我想使用
/comments
否则,如果我在用户页面中点击我得到的所有评论
/user/:user_id/comments
因此,如何配置以确保生成正确的页面。
如果我是你,我会这样做:
def index
@comment = Comment.find_by(user_id: params[:user_id], id: params[:id])
# It looked weird that you tried to find a @comment
# instead of @comments in action `index`
# I think you made a typing mistake and this can be help
@comments = Comment.where(user_id: params[:user_id])
end