Ruby on rails 如何为Rails中的嵌套路由共享控制器操作?
在Rails中,当我需要时:Ruby on rails 如何为Rails中的嵌套路由共享控制器操作?,ruby-on-rails,Ruby On Rails,在Rails中,当我需要时: /comments 及 如何最好地组织CommentsController?例如,让路由共享索引操作,或与两个控制器一起工作?我相信您希望/comments仅用于显示和索引操作,对吗?否则,在创建或更新注释时,post参数将丢失 在您的routes.rb中,您可以有如下内容: resources : posts do resources :comments end resources :comments, :only => [:index, :show]
/comments
及
如何最好地组织CommentsController?例如,让路由共享索引操作,或与两个控制器一起工作?我相信您希望
/comments
仅用于显示和索引操作,对吗?否则,在创建或更新注释时,post
参数将丢失
在您的routes.rb中,您可以有如下内容:
resources : posts do
resources :comments
end
resources :comments, :only => [:index, :show]
以您的形式:
form_for([@post, @comment]) do |f|
在控制器中,确保在处理注释之前找到帖子
(对于新建
,编辑
,创建
和更新
,例如:
@post = Post.find(params[:post_id])
@comment = @post...
我相信您只希望/comments
用于show
和index
操作,对吗?否则在创建或更新注释时,post
参数将丢失
在您的routes.rb中,您可以有如下内容:
resources : posts do
resources :comments
end
resources :comments, :only => [:index, :show]
以您的形式:
form_for([@post, @comment]) do |f|
在控制器中,确保在处理注释之前找到帖子
(对于新建
,编辑
,创建
和更新
,例如:
@post = Post.find(params[:post_id])
@comment = @post...
您只能使用一个控制器
我会使用before_filter
检查post_id
参数是否存在:
class CommentsController < ApplicationController
before_filter :find_post, only: [:index]
def index
if @post.present?
## Some stuff
else
## Other stuff
end
end
private
def find_post
@post = Post.find(params[:post_id]) unless params[:post_id].nil?
end
end
您只能使用一个控制器
我会使用before_filter
检查post_id
参数是否存在:
class CommentsController < ApplicationController
before_filter :find_post, only: [:index]
def index
if @post.present?
## Some stuff
else
## Other stuff
end
end
private
def find_post
@post = Post.find(params[:post_id]) unless params[:post_id].nil?
end
end
你可以用rails路线做任何你想做的事情
routes.rb
match 'posts/:id/comments', :controller => 'posts', :action => 'comments'}
resources :posts do
member do
get "comments"
end
end
你可以用rails路线做任何你想做的事情
routes.rb
match 'posts/:id/comments', :controller => 'posts', :action => 'comments'}
resources :posts do
member do
get "comments"
end
end
谢谢。所以,我理解我认为的路线部分,但我不确定这一点:“在你的控制器中,确保你总是在处理评论之前找到帖子”,意思是如果@post.present?;@post.comments;else;Comment.all;end?我只是不确定是否最好返回一个[]当@post为nil.Hmm.。这有意义吗?谢谢!一篇文章有很多评论,因此用于创建和编辑的url必须具有完整路径/posts/1/comments
,否则评论将不会链接到该文章。因此,您必须找到将接收评论的文章:@post=post.find(参数[:post\u id])
谢谢。因此,我理解我认为的路线部分,但我不确定这一点:“在控制器中,确保在处理评论之前始终找到帖子”,意思是如果@post.present?;@post.comments;else;Comment.all;end?我不确定是否最好返回一个[]当@post为nil.Hmm.。这有意义吗?谢谢!一篇文章有很多评论,因此用于创建和编辑的url必须具有完整路径/posts/1/comments
,否则评论将不会链接到该文章。因此,您必须找到将接收评论的文章:@post=post.find(参数[:post\u id])
Hmm..对不起,这个问题的表述很糟糕。我的问题是,如果找不到@post,\@评论将是空的,但是回复(200 OK)。但是,我需要404(找不到),如果\@post是空的。如何在控制器中共享该操作?在我给你的代码中,我想如果\@post没有找到,那么你将在\@comments中拥有来自每个post的所有评论,而不是它将是空的…但是如果你想的话,你可以在这种情况下提出404,检查这个:嗯…对不起,这个问题表述得很糟糕。我的问题如果找不到@post,\@注释将为空,但响应(200 OK)。然而,我需要404(找不到),如果\@post是空的。如何在控制器中共享该操作?在我给你的代码中,我想如果\@post没有找到,那么你将在\@comments中拥有来自每个post的所有评论,而不是它将是空的…但是如果你愿意,在这种情况下你可以提出404,请检查以下内容: