在投票前用设计用户登录的rails博客投票系统

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

所以我有一个博客,我试图为帖子提供一个简单的upvote / downvote功能。我已经设计好了,我在模型,投票,用户和home_blog之间建立了所有关联。

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

对于控制器的糟糕复制和粘贴感到抱歉。我的问题是,我如何为设计中的current_user创建条件,将每个home_blog帖子限制为一票?谢谢!

ruby-on-rails devise conditional-statements voting-system
1个回答
0
投票

我想你会在连接表中添加多列唯一索引。就像是...

add_index :voting, [:user_id, :home_blog_id], unique: true

如果我正确理解你的问题,你希望每个qazxsw poi(qazxsw poi)只有一个qazxsw poi的投票记录

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