在rails中为每个用户仅为帖子评分一次

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

我在允许用户评价帖子方面遇到了麻烦。我的任务是让用户只对帖子评分一次。在节目页面上,我的帖子包括评级的单选按钮。如果用户第二次尝试评级,则需要更新用户对同一帖子的先前评级。我面临的问题是用户能够多次评价帖子。怎么解决这个?

用户模型:

class User < ApplicationRecord
  has_many :posts
  has_many :ratings
end

发布模型:

class Post < ApplicationRecord
  has_many :ratings
  belongs_to :user
end

评级模型

class Rating < ApplicationRecord
  belongs_to :post
  belongs_to :user
end

在帖子控制器中,我使用嵌套属性进行评级。

def show
  @post = @topic.posts.find(params[:id])
  @rate = @post.ratings.all
  @rate = Rating.where(post_id: @post.id).group("rate").count
end

private def post_params
  params.require(:post).permit(:title, :body, ratings_attributes: [:rate])
end

帖子的显示页面包括使用<fieldset>创建评级:

<%= form_for [@topic, @post] do |f| %>
  <%= f.fields_for :ratings, @post.ratings.build do |builder| %>
    <fieldset>
      <% for i in 1..5 %>
        <%= builder.radio_button :rate, i %><%= i %>
      <% end %>
    </fieldset>
  <% end %>
  <%=f.submit "Rate" %>
<% end %>
ruby-on-rails nested-attributes
2个回答
0
投票

您可以先使用,也可以像这样初始化

   @rating=Rating.where(post_id: @post.id,user_id: current_user).first_or_initialize

2
投票

首先,在评级中添加验证,以强制用户和帖子组合的唯一性。这将停止创建重复评级。

validates_uniqueness_of :post_id, scope: :user_id

然后,在保存评级的操作中,首先检查是否有可以更新的记录,否则创建一个新记录。

@rating = Rating.find_or_initialize_by(user: @user, post: @post)
@rating.rate = params[:rate]
@rating.save

这可能不是完美的语法,但您应该了解您尝试做什么,并可以调整以匹配您的代码。

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