在投票前用设计用户登录的rails博客投票系统
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在投票前用设计用户登录的rails博客投票系统相关的知识,希望对你有一定的参考价值。
所以我有一个博客,我试图为帖子提供一个简单的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帖子限制为一票?谢谢!
答案
我想你会在连接表中添加多列唯一索引。就像是...
add_index :voting, [:user_id, :home_blog_id], unique: true
如果我正确理解你的问题,你希望每个qazxsw poi(qazxsw poi)只有一个qazxsw poi的投票记录
以上是关于在投票前用设计用户登录的rails博客投票系统的主要内容,如果未能解决你的问题,请参考以下文章