2011-11-23 77 views
7

我有選民模式加入的用戶和問題。用戶可以對問題進行投票。他們可以上下投票(這是在選舉模式中記錄的)。首先,我希望能夠防止用戶在一個方向上投多個選票。其次,我想讓用戶投反對票。所以,如果他們投了票,他們仍然應該能夠投票決定哪一個取代最後的投票。用戶應該永遠不能對問題投票兩次。這裏是我的文件:如何驗證has_many的唯一性:通過連接模型?

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 

回答

10

你會把唯一性約束放在Votership模型上。您不需要對關聯本身進行驗證。

這意味着用戶只能對給定問題(向上或向下)進行一次投票。

+0

嗨,這工作,但增加在連接表中的重複的條目時,它提出了一個'的ActiveRecord :: ValidateError'例外。關聯記錄的最佳方式是什麼?如果沒有引發異常,最好的方法是什麼?謝謝 –

+0

是不是應該引發驗證錯誤?如果每個用戶只需要投一票,那麼您需要刪除先前的投票(並用新的投票代替),或者在出現錯誤時將其解救出來,然後決定如何執行。這聽起來像是對重複條目的驗證失敗,這正是它應該做的,不是嗎? – jefflunt

+0

是的,我只是問,因爲我是新來的鐵軌,我想知道是否有更好的方法(像一個''',不會引發異常)挽救異常。感謝您的回答 –

0

關係模型:

class Person 
    has_many :accounts 
    has_many :computers, through: :accounts 
end 

class Account 
    belongs_to :person 
    belongs_to :computer 

    scope :administrators, -> { where(role: 'administrator') } 
end 

class Computer 
    has_many :accounts 
    has_many :people, through: :accounts 
end 

這是它是如何叫

person.accounts.administrators.map(&:computer)

我們可以使用ActiveRecord :: SpawnMethods#合併做得更好!

person.computers.merge(Account.administrators)


編號:https://coderwall.com/p/9xk6ra/rails-filter-using-join-model-on-has_many-through

相關問題