To the point: I want to put Post has_many Comments but I do not want to create a separate comment controller and subsequent views. Mainly because the comment开发者_运维问答s will never show up anywhere else but inside the SHOW action of a Post. Or am I breaking the MVC paradigm?
You are breaking the MVC paradigm, as you said. The point of MVC is to split everything up into bite-size chunks so it is more manageable. That's how I see it at least.
How would comments be created without a specific controller for them. The showing part on a Post
is the easy part:
@comments = @post.comments
There is a fundamental distinction to be made between the internal domain model of your system and the public interface your system exposes.
If you are using a relational database, it is good practice to have
Comment.belongs_to :post
Post.has_many :comments
The internal domain model of your system can help you design your public interface - but you can also tailor your public interface how you want it, without being forced to make it a strict reflection of your internal domain model!
In your case, I would suggest having a CommentsController
. But in this controller class, you do not need all of the normal REST actions. You only need a few of them.
# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
respond_to :js
def create
@post = Post.find(params[:post_id])
@comment = post.comments.create(params[:comment])
respond_with [@post, @comment]
end
end
In this controller, you only have a create
action which would be the target of the "new comment" form at the bottom of the page displaying a post. You do not need any of the other REST actions because people never view, edit, or delete a comment in isolation - they only create new ones, and not from a dedicated new-comment page either. The routing for this is as follows:
# config/routes.rb
MyApp::Application.routes.draw do
resources :posts do
resources :comments, :only => [:create]
end
end
The more you deviate from the MVC paradigm, the more problems you'll have later on. For example, if you wanted to add admin views for your Comments, it would be easier to expand on it through the Comments Controller. Else, you'll end up having multiple actions for your comment in the Posts controller (eg. approve_comment, delete_comment, voteup_comment, etc).
That being said, you can always wire things up so that actions on your comments direct the user back to the Post that originated it. So, comment related actions will reside in the Comments Controller, but the user is generally working with Posts (and its associated Comments).
精彩评论