如何检查用户是否已对书籍进行了评分

问题描述 投票:1回答:1

我想为我的图书馆应用制作Google Play等评论系统,这意味着1位用户只需提交评论1次,下次将进行编辑评论

https://imgur.com/a/RciVuln

这是我到目前为止:

在Book / show.html.erb中

     <div class="col-md-7 col-md-offset-1">
      <% @book.reviews.each do |r| %>
        <div class = "reviews" >
          <div class="star-rating" data-score= <%= r.rating %></div>
          <%= link_to r.user.name, r%>
          <p><%= r.comment %></p>
        </div>
      <% end %>    
     </div>
     </div>

     <script>
 $('.star-rating').raty({
    path: '/assets/',
    readOnly: true,
    score: function() {
      return $(this).attr('data-score');
    }
  });
     </script>

在reviews_controller中

    def update
    @reviews = Reviews.find_by(params[:id])
    @review.update_attributes(reviews_params)
    @book  = Book.find(@review.book_id)
    flash[:success] = "Comment updated"
    redirect_to @book
    end

    def edit
    @review = Review.find(params[:id])
    end

在reviews / edit.html.erb中:

    <%= form_for(@review) do |f| %>
    <%= f.error_notification message: 
     f.object.errors[:base].to_sentence if 
     f.object.errors[:base].present? %>
    <div class="field">
    <div id="star-rating"></div>
    </div>
    <%= f.label :comment %>
    <%= f.text_area :comment, class: 'text-area' %>
    <%= f.hidden_field :book_id%>
   <div>

   <div class="form-actions">
   <%= f.button :submit, class:"btn btn-primary" %>
   </div>
   <% end %>
   <script>
   $('#star-rating').raty({
    path: '/assets/',
    scoreName: 'review[rating]'
   });
   </script>

我不知道rails是否具有使用该书的用户评论ID来检查当前用户的id的功能

ruby-on-rails ruby
1个回答
1
投票

您想要的是在审阅模型上添加验证约束。

class Review
  belongs_to :user
  belongs_to :book

  validates :book_id, uniqueness: { scope: :user_id }
end

验证子句可以读作“验证给定user_id的book_id的唯一性”。

因此,如果用户尝试为他/她已经审阅过的图书创建评论,则验证将是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.