How can I verify the uniqueness of has_many: through the connection model?

I have users and problems associated with the voter model. Users can vote on questions. They can either vote up or down (as recorded in the voter model). Firstly, I want users to not be able to cast multiple votes in one direction. Secondly, I want to allow users to do the opposite vote. So, if they voted, they still have to vote, which will replace the vote. Users should never be able to vote on a problem 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 
+7
source share
2 answers

You have set the uniqueness constraint in the Votership model. You do not need to put checks on the association itself.

 class Votership < ActiveRecord::Base belongs_to :user belongs_to :issue validates :issue_id, :uniqueness => {:scope=>:user_id} end 

This means that the user can have only one vote on a given problem (up or down).

+10
source

Relationship Models:

 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 

That's what it's called

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

We can do it better using ActiveRecord :: SpawnMethods # merge!

person.computers.merge(Account.administrators)


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

0
source

All Articles