I’m working on implementing boards.
Now I have BoardsController and PostsController.
By default, posts are nested by boards.
I want all board’s post list have their special route using same PostsController
so I did this in route.rb
resources :notice, :controller => "posts", :board_id => 1
resources :faq, :controller => "posts", :board_id => 2
resources :qna, :controller => "posts", :board_id => 3
At first, it seems to work. But I realized a problem.
because i used same ‘PostsController’ in these resources.
Codes related to path are same when doing controller’s action
like,
posts_controller
def create
@post = Board.find(params[:board_id]).posts.build(params[:post])
if @post.save
redirect_to board_posts_path(@post.board_id)
else
render 'new'
end
end
when I go to localhost:3000/notice/new, it works fine
but when I submitted the new post, controller redirects to localhost:3000/boards/1/posts/
because of redirect_to board_posts_path(@post.board_id)
and that’s not what I want.
I could handle this using if statements, but it seems messy.
Is there any proper solution to this?
You can use the
self.sendon the controller to dynamically resolve the path by the post type. Assuming you have the type of the created post in a string ( I didn’t understand from your question if Notice < Post and if you use Single Table Inheritance):