I have a difficulty with something that makes me think I don't understand an aspect of Rails what. I've made a sort of blog site, and under each article I show the comments and a comment form. The comment model validates whether the user has entered his name. When he hasn't, I want to send him back to the form with his comment text still there. In the comment/create action, I now have if @comment.save ... (no problem here) else flash[:commentnotice]="Comment could not be stored" redirect_to :back end The problem is that after the redirect, the user gets an empty comment form again and has lost his text. In Rails tutorials, they generally use render instead of a redirect in case of validation failure. That way the current contents of the @comment object would be used to prefill the form and the user would see his text. However, just rendering the same page again is difficult for me for two reasons: 1) the comment form can be under different kinds of pages (news posts, photo albums, ...) so to know which page to render I have to store the page info in hidden fields of the form? or is there a better way 2) before I can render the page I have to call the controller action that loads the article or photo album, but this will also create a new comment for the comment form. I could just check if @comment already exists? If there is an elegant solution for this typical situation I'd be grateful to learn about it. Tia!
on 2006-03-07 18:33
on 2006-03-07 18:58
A redirect is a new request, so the model is lost. I solved this by putting the model object in the flash (on errors) and then checking for it in the view. The model object will also have its errors, so pulling it out in the page does double duty: the input values are available again as well as the validation errors. b
on 2006-03-07 20:48
Ben M. wrote: > A redirect is a new request, so the model is lost. I solved this by > putting the model > object in the flash (on errors) and then checking for it in the view. > The model object > will also have its errors, so pulling it out in the page does double > duty: the input > values are available again as well as the validation errors. > > b Thanx! Got my elegant solution :)