基于Ajax的评论

时间:2011-01-24 17:53:40

标签: ruby-on-rails

评论模型

  belongs_to :post
  validates_presence_of :username
  validates_presence_of :body

发布模型

  has_many :comments

posts_controller

def show
 @post = Post.find(params[:id])
 @comments = @post.comments
 @comment = Comment.new
end

comments_controler

def create
 @comment = Comment.new(params[:comment])
 if @comment.save
     @comments = @comment.post.comments
     respond_to do |format|
        format.js
     end
 else
     #what to do in here
 end
end

create.js

$("#comments").html("<%= escape_javascript(render :partial => "comments", :collections => @comments) %>");

发布show.html

<div id="comments">
 <%= render :partial => "comments", :collection => @comments %>
</div>
<div id="comment-form">
 <%= form_for(@comment, :method => :put, :remote => true) do |f| %>

 <% if @comment.errors.any? %>
 <div id="error_explanation">
 <% @comment.errors.full_messages.each do |msg| %>
 <%= msg %>
 <% end %>
 </div>
 <% end %>

 <%= f.text_field :username %>
 <%= f.text_area :body %>
 <%= f.hidden_field :post_id, :value => @post.id  %>
 <%= f.submit %>

 <% end %>
</div>

我想在comments_controller中编写一些注释创建操作的内容,这样我就可以在不重新加载页面的情况下显示验证错误。任何帮助将不胜感激。如果有其他解决方案可以进行基于ajax的评论,我也可以更改所有代码。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

else 
  respond_to do |format|
    format.js {
      render :text => "oops"
      # or 
      render :partial => "/comments/error_message", :locals => {:comment => @comment} # @comment.errors would contain the validation errors
    }
  end
end