【发布时间】:2010-04-23 17:02:17
【问题描述】:
我已经使用 Ruby on Rails 构建了一个博客。两者都是新手。在进入错误处理部分之前,我正在非常有效地实现 AJAX。
我允许在帖子上使用 cmets,并通过在 /views/posts/show.html.erb 页面中呈现评论部分和远程表单来做到这一点。成功保存评论后,会使用views/cmets/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/cmets/_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/cmets/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
评论控制器#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
【问题讨论】:
-
请注意,您实际上是通过
create!和save两次尝试保存记录。虽然与问题无关:) -
啊,就像我说的,对这个很陌生。你会删除创建!方法?
-
我认为@post.cmets.build(params[:comment]) 可能会更好
标签: ruby-on-rails ruby error-handling