我使用Ruby on Rails构建了一个博客。两者都是新的。我正在非常有效地实现AJAX,直到我进入错误处理部分。
我允许对帖子发表评论,并通过在/views/posts/show.html.erb页面中呈现评论部分和远程表单来执行此操作。成功保存评论后,使用views / comments / create.js.rjs更新节目页面并显示闪光通知。
我只是试图在没有保存时闪现通知。搜索并自己研究了一下。无法让它飞起来。这是我的代码:
/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#创建
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
答案 0 :(得分:0)
创造!是一个问题因为创造!当模型无效时引发异常,这意味着它下面的respond_to代码将不会执行。
就像科里所说,取代创造!与构建。你通过rjs显示flash通知的策略可能就好了。