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

时间:2018-09-05 01:01:26

标签: ruby-on-rails devise conditional-statements voting-system

所以我有一个博客,我试图为帖子提供一个简单的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

对于控制器的the脚复制和粘贴感到抱歉。我的问题是,我该如何为current_user设计一个条件以将其限制为每个home_blog帖子只能投票一次?谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您应该在联接表中添加多列唯一索引。像...

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

如果我正确理解了您的问题,那么您希望每个home_blogcurrent_user)只有user_id的投票记录