如何验证 has_many 的唯一性:通过连接模型? [英] How do I validate the uniqueness of a has_many :through join model?
问题描述
我将用户和问题加入到投票模型中.用户可以对问题进行投票.他们可以投赞成票或反对票(记录在选民模型中).首先,我希望能够防止用户在一个方向上投多票.其次,我想让用户投反对票.所以,如果他们投了赞成票,他们应该仍然能够投反对票,这将取代赞成票.用户永远不能对一个问题进行两次投票.这是我的文件:
I have users and issues joined by a votership model. Users can vote on issues. They can either vote up or down (which is recorded in the votership model). First, I want to be able to prevent users from casting multiple votes in one direction. Second, I want to allow users to cast the opposite vote. So, if they voted up, they should still be able to vote down which will replace the up vote. Users should never be able to vote on an issue twice. Here are my files:
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, :presence => true,
: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 => :associations
has_many :voterships, :dependent => :destroy
has_many :issues, :through => :voterships
end
推荐答案
您会将唯一性约束放在 Votership
模型上.您不需要对关联本身进行验证.
You would put the uniqueness constraint on the Votership
model. You don't need to put validations on the association itself.
class Votership < ActiveRecord::Base
belongs_to :user
belongs_to :issue
validates :issue_id, :uniqueness => {:scope=>:user_id}
end
这意味着用户只能对给定的问题(向上或向下)投一票.
This means a user can only have a single vote on a given issue (up or down).
这篇关于如何验证 has_many 的唯一性:通过连接模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!