注释部分在rails中使用ajax时无法正常工作



我是 rails 的新手,我正在尝试在不重新加载该页面的情况下为项目添加评论。但是当我点击提交时,它向我显示了重复的评论,并且没有显示之前所做的评分点。如果我刷新该页面,一切都会恢复正常。

在我的路线中.rb:

resources :items do 
  resources :reviews
end

在 review_controller.rb 中:

def create
    @review = Review.new(review_params)
    @review.item_id = @item.id
    @review.user_id = current_user.id
    respond_to do |format|
        if @review.save
          format.js
          format.html { redirect_to item_path(@item)}
        else
            format.html { render :new}
        end
    end
end

在视图/评论/创建.js.erb

$('#new-review').parent().append("<%= j render @item.reviews %>");

在视图/项目/显示.html.erb

<div class = "row">
 <div class = "col-md-4">
   <div id = 'new-review'>
      <%= render @item.reviews %>
   </div>
 </div> 
</div>
<h2>Add review</h2>
<%= render "reviews/form" %>
//adding star rating 
<script>
$('.average-review-rating').raty({
    readOnly: true,
    path: '/assets/',
    score: function() {
        return $(this).attr('data-score')
    }
});
</script>
<script>
$('.review-rating').raty({
readOnly: true,
path: '/assets/', 
score: function() {
return $(this).attr('data-score');
}
});
</script>

在评论/_form.html.erb:

<%= form_for([@item, @item.reviews.build], remote: true) do |f|  %>
  <div id ="rating-form">
    <label>Rating</label>
  </div>
 <%= f.label :comment %> 
 <%= f.text_field :comment, class: "form-control" %>
 <%= f.button :submit %>
<% end %>
<script>
$('#rating-form').raty({
    path: '/assets/',
    scoreName: 'review[rating]'
});
</script>    
I took the rating star from jquery.raty
And this is what happened:

 [1]: https://i.stack.imgur.com/fkaFP.png

如我所见,您应该在单独的部分中单独布局以供审查,然后仅加载*.js.erb文件中。你现在每次都再次渲染@item.reviews。用于评级的JS代码也应该在*.js.erb文件中,以便在ajax上启动完成。

最新更新