加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何验证has_many的唯一性:通过连接模型?

发布时间:2020-12-16 19:19:33 所属栏目:百科 来源:网络整理
导读:我有一个选民模型加入的用户和问题.用户可以对问题进行投票.他们可以向上或向下投票(在选民模型中记录).首先,我希望能够阻止用户在一个方向上投票.其次,我想允许用户投反对票.因此,如果他们投了票,他们仍然可以投票,这将取代上行投票.用户永远不能对问题进行
我有一个选民模型加入的用户和问题.用户可以对问题进行投票.他们可以向上或向下投票(在选民模型中记录).首先,我希望能够阻止用户在一个方向上投票.其次,我想允许用户投反对票.因此,如果他们投了票,他们仍然可以投票,这将取代上行投票.用户永远不能对问题进行两次投票.这是我的文件:
class Issue < ActiveRecord::Base
  has_many :associations,:dependent => :destroy

  has_many :users,:through => :associations

  has_many :voterships,:dependent => :destroy
  has_many :users,:through => :voterships

  belongs_to :app

  STATUS = ['Open','Closed']

  validates :subject,:presence => true,:length => { :maximum => 50 }
  validates :description,:length => { :maximum => 200 }
  validates :type,:presence => true
  validates :status,:presence => true

  def cast_vote_up!(user_id,direction)
    voterships.create!(:issue_id => self.id,:user_id   => user_id,:direction => direction)
  end
end


class Votership < ActiveRecord::Base
  belongs_to :user
  belongs_to :issue
end

class VotershipsController < ApplicationController
  def create
    session[:return_to] = request.referrer
    @issue = Issue.find(params[:votership][:issue_id])
    @issue.cast_vote_up!(current_user.id,"up")
    redirect_to session[:return_to]
  end
end

class User < ActiveRecord::Base
  authenticates_with_sorcery!

  attr_accessible :email,:password,:password_confirmation

  validates_confirmation_of :password
  validates_presence_of :password,:on => :create
  validates_presence_of :email
  validates_uniqueness_of :email

  has_many :associations,:dependent => :destroy
  has_many :issues,:through => :voterships
end

解决方法

您可以将唯一性约束放在Votership模型上.您不需要在关联本身上放置验证.
class Votership < ActiveRecord::Base
  belongs_to :user
  belongs_to :issue

  validates :issue_id,:uniqueness => {:scope=>:user_id}
end

这意味着用户只能对给定的问题(向上或向下)进行一次投票.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读