I have built a blog using Ruby on Rails. New to both. I am implementing AJAX pretty effectively until I get to the error handling portion.
I allow for comments on posts and do this by rendering a comment partial and remote form in the /views/posts/show.html.erb page. Upon successful save of a comment the show page is updated using views/comments/create.js.rjs and displays a flash notice.
I am simply trying to flash a notice when it doesn't save. Searched around and worked this a bit on my own. Can't get it to fly. Here is my code:
/views/posts/show.html.erb
<div id="comments">
<%= render :partial => @post.comments %>
<div id="notice"><%= flash[:notice] %></div>
</div>
<% remote_form_for [@post, Comment.new] do |f| %>
<p>
<%= f.label :body, "New Comment" %><br/>
<%= f.text_area (:body, :class => "textarea") %>
</p>
<p>
<%= f.label :name, "Name" %><br/>
<%= f.text_field (:name, :class => "textfield") %>
</p>
<p>
<%= f.label :email, "Email" %><br/>
<%= f.text_field (:email, :class => "textfield") %>
</p>
<p><%= f.submit "Add Comment" %></p>
<% end %>
/views/comments/_comment.html.erb
<% div_for comment do %>
<div id="comment-wrapper">
<% if admin? %>
<div id="comment-destroy"><%=link_to_remote "X", :url => [@post, comment], :method => :delete %></div>
<% end %>
<%= h(comment.body) %><br/><br/>
<div class="small">Posted <%= time_ago_in_words(comment.created_at) %> ago by <%= h(comment.name) %>
<% if admin? %>
| <%= h(comment.email) %>
<% end %></div>
</div>
<% end %>
/views/comments/create.js.rjs
page.insert_html :bottom, :comments, :partial => @comment
page[@comment].visual_effect :highlight
page[:new_comment].reset
page.replace_html :notice, flash[:notice]
flash.discard
CommentsController#create
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create!(params[:comment])
respond_to do |format|
if @comment.save
flash[:notice] = "Thanks for adding this comment"
format.html { redirect_to @post }
format.js
else
flash[:notice] = "Make sure you include your name and a valid email address"
format.html { redirect_to @post }
fo开发者_C百科rmat.js
end
end
end
The create! is a problem because create! raises an exception when the model is invalid, meaning the respond_to code below it will not execute.
Like Corey says, replace create! with build. Your strategy of displaying the flash notice via rjs may well work then.
精彩评论