在Rails中使用Ajax时,注释部分无法正常工作

时间:2019-06-20 02:55:50

标签: ruby-on-rails ajax

我是Rails的新手,我想为某个商品添加评论,而无需重新加载该页面。但是,当我单击“提交”时,它向我显示了重复的评论,但没有显示以前做出的评分。如果刷新该页面,一切将恢复正常。

在我的routes.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

在views / reviews / create.js.erb

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

在views / items / show.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>

在reviews / _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

1 个答案:

答案 0 :(得分:0)

正如我所看到的,您应该将审阅的布局分成单独的部分,然后仅将其加载到*.js.erb文件中。您现在每次都重新渲染@item.reviews。用于评级的JS代码也应位于*.js.erb文件中,以便在ajax完成时启动。