I have an article model and a comment model. I currently have two separate forms to create new comments: one that allows the user to specify the name of the article their comment is for and a one underneath an article show view that creates new comments for that article. I am using form_for @comment in the first case and form_for [@article, @comment] in the second case. When a user specifies an article name as a string I convert it to an article id before saving the comment.
My routes are
resources :comments
resources :articles do
resources :comments
end
For the second form how can I redirect back to the article on a failed comment save (validations and errors should be displayed)? For the first form I just redirect to the homepage as that is where my first comment form is.
Also, I have a validation on the first form that the article name field cannot be empty. How can I remove this validation for the second form as the user does not need to specify an article name?
My new function in the comments_controller handles both forms. How do I determine which form is being submitted in the controller?
Thanks in advance.
Actually redirecting isn’t the way to go here, I’d say. Error and validation handling in Rails usually works the way that you re-render the form in the
createorupdatemethod with the validated object(s) instead of actually redirecting to theneworeditpage.As for your problem with the two versions of comments saving, I would use
form_for @commentin both versions. Dump the nested form version simulate the user’s behavior with the given article string in your form. This way you could spare a lot of if-else statements.As for the rendering on validation errors part, you could simply check if you have an article_id in your params (which means your creating/updating a comment through a given article) or not (which means you have the first version).
Some code to elaborate:
Hope this helps.