我已经使用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#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
最佳答案
创造!是一个问题,因为创建!当模型无效时会引发异常,这意味着它将不执行其下的response_to代码。
如Corey所说,替换create!与建立。那么,通过rjs显示即时通知的策略可能会起作用。
关于ruby-on-rails - 使用AJAX显示错误消息Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2700466/