Model Validation with Multiple Models and Good MVC Design

  1. Model Validation With Multiple Controllers Involved
    I have a Posts controller and model and a Comments controller and
    model. Posts has a show method and a corresponding view that shows a
    post and its associated comments, which are rendered with a partial
    from comments. Another partial from comments is used to allow the user
    to add their comment to the page.

Problem: If a user tries to add a new comment but it fails the comment
model validation, how do I get back to the show page from posts and
display the model validation error for the new comment?

views/posts/show.rhtml
#spit out the details of the post

#render the existing comments and let a user make a new one

Comments

<%= render :partial => "comments/comment", :collection => @post.comments %> <%= render :partial => "comments/new"%>

controllers/comments_controller.rb
#new method unnecessary because the “comments/new” partial never calls
it?
def new
@comment = Comment.new
end

def create
@comment = Comment.new(params[:comment])
if @comment.save
redirect_to :controller => “posts”, :action => “show”, :id =>
@comment.post
else
#we’re over in the comments controller - how do we get our data
validation errors from the
#comments model back over to the show page of posts?
render :controller => “posts”, :action => “show”
end

  1. Good MVC Design
    OK so for my little blog app at first I had just one controller, blog,
    and just kept adding methods there like add_post, add_comment, etc. It
    seemed like maybe that was a bad idea so I decided to use three
    controllers instead of one: blog, posts, and comments. Blog would be
    light-weight and not have to care about the details of posts or
    comments. But then I ran into the problem described above.

What would be the most natural way to structure this kind of thing
with MVC, one blog controller with double-barelled methods like
add_post, add_comment etc. or a bunch of controllers like posts,
comments, etc. that do all the heavy lifting?

Thanks,
Yink