Using AJAX to display error message Ruby on Rails
Posted
by bgadoci
on Stack Overflow
See other posts from Stack Overflow
or by bgadoci
Published on 2010-04-23T17:02:17Z
Indexed on
2010/04/23
17:03 UTC
Read the original article
Hit count: 274
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 }
format.js
end
end
end
© Stack Overflow or respective owner