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?

#spit out the details of the post

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


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

#new method unnecessary because the “comments/new” partial never calls
def new
@comment =

def create
@comment =[:comment])
redirect_to :controller => “posts”, :action => “show”, :id =>
#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”

  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?


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs