Railsでは、必要な場合:
/comments
と
/posts/1/comments
CommentsControllerを最適に整理するにはどうすればよいですか?たとえば、ルートでインデックスアクションを共有したり、2つのコントローラーで動作させたりしますか?
Railsでは、必要な場合:
/comments
と
/posts/1/comments
CommentsControllerを最適に整理するにはどうすればよいですか?たとえば、ルートでインデックスアクションを共有したり、2つのコントローラーで動作させたりしますか?
1つのコントローラーのみで作業できます。
パラメータが存在before_filter
するかどうかを確認するためにaを使用します。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
そしてあなたのルートに(あなたの選択の制約で)持っている:
resources :posts do
resources :comments
end
resources :comments
私はあなたが行動の/comments
ためだけに欲しいshow
と思いますよね?index
そうしpost
ないと、を作成または更新するときにパラメータが失われcomment
ます。
あなたの中にroutes.rb
あなたは次のようなものを持つことができます:
resources : posts do
resources :comments
end
resources :comments, :only => [:index, :show]
あなたのフォームで:
form_for([@post, @comment]) do |f|
また、コントローラーで、 (、、、および、のように、post
を処理する前に必ず見つけてください。comments
new
edit
create
update
@post = Post.find(params[:post_id])
@comment = @post...
Railsルートでやりたいことはほとんど何でもできます。
ルート.rb
match 'posts/:id/comments', :controller => 'posts', :action => 'comments'}
resources :posts do
member do
get "comments"
end
end