If you can use ajax then you can have one controller per model. For example, the view post page could have an ajax form that submits to the comments controller.
That said, I think it's a bad thing if you have to change the behavior of your application to be able to structure your code in a nice way.
So Rails has a nice built-in solution for you: nested resources.
Put this in your routes.rb file:
Code ruby:
map.resources :posts do |posts|
posts.resources :comments
end
This gives you the following urls:
Code:
/posts
/posts/3
/posts/3/comments/create
But you can still have separate controllers for posts and comments.
Code ruby:
class PostsController < ApplicationController
# /posts
def index
@posts = Post.find(:all)
end
# /posts/3
def show
@post = Post.find(params[:id])
end
end
class CommentsController < ApplicationController
# /posts/3/comments/create
def create
@post = Post.find(params[:post_id]) # params[:post_id] contains the "3" from the url
@comment = @post.comments.new(params[:comment])
...
end
end
This is useful if you want to have two controllers. I cannot think of any reason why you'd want to merge the two controllers into one, but there might be a good reason depending on your application. For this situation of posts-comments, nested routes are the standard way of doing this in Rails.
Bookmarks