我已經使用Ruby on Rails構建了一個博客。兩者都是新的。我非常有效地實現AJAX,直到遇到錯誤處理部分。使用AJAX顯示錯誤消息Ruby on Rails
我允許對帖子發表評論,並通過在/views/posts/show.html.erb頁面中提供評論部分和遠程表單來完成此操作。成功保存評論後,顯示頁面將使用views/comments/create.js.rjs進行更新,並顯示Flash通知。
我只是試圖刷新通知時,它不保存。搜索了一下,並自己做了一些工作。無法讓它飛行。這裏是我的代碼:
/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 %>
/視圖/評論/創建。 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
注意你實際上試圖通過'create!'和save'保存記錄兩次。不過,這個問題並不相關:) – 2010-04-23 17:06:10
啊,就像我剛纔說的那樣,新的。你會刪除創建!方法? – bgadoci 2010-04-23 17:07:15
我覺得@ post.comments.build(params [:comment])可能會更好 – Corey 2010-04-23 17:19:16