It’s rare for Rails 3 and Googling to each fail to solve the following problem, while most tutorials do not deal with processing errors.
I created a Rails 3 project with several types / models of content such as articles, blogs, etc. Each type of content has comments; all of them are stored in one comment table as an embedded resource and with polymorphic associations. There is only one action for comments, the “create” action, because there is no need for a show, etc., since it is a type of parental content and should just redraw this page when submitted.
Now I have most of this work, and comments are sent and published just fine, but the last remaining problem is errors when the user does not fill out the required field. If the fields are not filled, he should return to the parent page and display validation errors, such as Rails, usually with MVC.
The action of my comment controller looks like this, and this is what I tried first ...
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
respond_to do |format|
if @comment.save
format.html { redirect_to(@commentable, :notice => 'Comment was successfully created.') }
else
format.html { redirect_to @commentable }
format.xml { render :xml => @commentable.errors, :status => :unprocessable_entity }
end
end
end
When you do not fill out anything and submit a comment form, the page redirects the corresponding parent element back to it, but not a single flash or anything is displayed. Now I understand why, as I understand it, the flash will not be saved on redirect_to, only on the render. Now here is the problem.
"create", "blogs/show" (. , , , ). "else" ...
else
format.html { render 'blogs/show' }
format.xml { render :xml => @commentable.errors, :status => :unprocessable_entity }
end
, , " [...]/app/views/blogs/show.html.erb, # 1 : undefined `title ' nil: NilClass."
URL-, , , ... , /blogs/the -title-of-my-article ( friendly_id), /blogs/the -title- --/. , "" .
, , ? ?
, , route.rb / ...
resources :blogs, :only => [:show] do
resources :comments, :only => [:create]
end