【问题标题】:Comment section doen not work correctly when using ajax in rails在 Rails 中使用 ajax 时,注释部分无法正常工作
【发布时间】:2019-06-20 02:55:50
【问题描述】:

我是 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

在意见/评论/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>

在评论/_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

【问题讨论】:

    标签: ruby-on-rails ajax


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多