Ruby on rails rails博客投票系统,在投票前设计用户登录

Ruby on rails rails博客投票系统,在投票前设计用户登录,ruby-on-rails,devise,conditional-statements,voting-system,Ruby On Rails,Devise,Conditional Statements,Voting System,所以我有一个博客,我试图为帖子提供一个简单的向上投票/向下投票功能。我设计并建立了模型、投票、用户和家庭博客之间的所有关联 class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable,

所以我有一个博客,我试图为帖子提供一个简单的向上投票/向下投票功能。我设计并建立了模型、投票、用户和家庭博客之间的所有关联

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :liked_home_blogs, through: :votings
end

class HomeBlog < ApplicationRecord
  mount_uploader :image, ImageUploader
  has_many :hashtaggings
  has_many :hashtags, through: :hashtaggings
  has_many :votings
  has_many :votants, through: :votings

  def all_hashes=(names)
    self.hashtags = names.split(",").map do |name|
      Hashtag.where(name: name.strip).first_or_create!
    end
  end

  def all_hashes
    self.hashtags.map(&:name).join(", ")
  end
end

class Voting < ApplicationRecord
  belongs_to :home_blog
  belongs_to :user 
end
class用户
控制器现在看起来是这样的:

class VotingsController < ApplicationController

  before_action :authenticate_user!

def upvote
    @votings = HomeBlog.find(params[:home_blog_id])
    @votings.votings.build( :upvote => true, :downvote => false, 
:user_id => current_user.id)
    @votings.save!
      redirect_to request.referrer, notice: "Thanks for the 
 vote!"
 end



     def downvote
        @voting = HomeBlog.find(params[:home_blog_id])
        @voting.votings.build( :downvote => true, :upvote => 
    false, :user_id => current_user.id)
        @voting.save!
          redirect_to request.referrer, notice: "Thanks for the 
    vote!"
      end
private 

def voting_params
          params.require(:voting).permit(:upvote, :downvote, 
     :home_blog_id, :user_id)
 end

end
class VotingsControllertrue,:downvote=>false,
:user\u id=>current\u user.id)
@救命!
将_重定向到request.referer,注意:“感谢您的帮助
投票!”
结束
def否决票
@投票=HomeBlog.find(参数[:home\u blog\u id])
@voting.votings.build(:downvote=>true,:upvote=>
false,:user\u id=>current\u user.id)
@投票,救命!
将_重定向到request.referer,注意:“感谢您的帮助
投票!”
结束
私有的
def投票参数
参数要求(:投票)。允许(:向上投票,:向下投票,
:home\u blog\u id,:user\u id)
结束
结束

很抱歉控制器的复制和粘贴很糟糕。我的问题是,我如何为Desive中的当前用户设定一个条件,将他们限制在每篇家庭博客文章的一票之内?谢谢

我认为您应该将多列唯一索引添加到联接表中。类似于

add_index :voting, [:user_id, :home_blog_id], unique: true
如果我正确理解了您的问题,您希望每个
当前用户的
主页博客
只有一条投票记录(
用户id