diff --git a/app/models/budget/investment.rb b/app/models/budget/investment.rb index 1b528a9cb..fc157a999 100644 --- a/app/models/budget/investment.rb +++ b/app/models/budget/investment.rb @@ -257,7 +257,7 @@ class Budget end def can_vote_in_another_heading?(user) - headings_voted_by_user(user).count < group.max_votable_headings + user.headings_voted_within_group(group).count < group.max_votable_headings end def headings_voted_by_user(user) @@ -265,7 +265,7 @@ class Budget end def voted_in?(heading, user) - headings_voted_by_user(user).include?(heading.id) + user.headings_voted_within_group(group).where(id: heading.id).exists? end def ballotable_by?(user) diff --git a/app/models/user.rb b/app/models/user.rb index 3a274f056..6aaf634ef 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -127,6 +127,11 @@ class User < ActiveRecord::Base votes.for_budget_investments(Budget::Investment.where(group: group)).exists? end + def headings_voted_within_group(group) + voted_investments = votes.for_budget_investments(Budget::Investment.by_group(group.id)).votables + Budget::Heading.where(id: voted_investments.map(&:heading_id).uniq) + end + def administrator? administrator.present? end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 1d860e121..d32b8fa17 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -2,6 +2,35 @@ require 'rails_helper' describe User do + describe '#headings_voted_within_group' do + it "returns the headings voted by a user" do + user1 = create(:user) + user2 = create(:user) + + budget = create(:budget) + group = create(:budget_group, budget: budget) + + new_york = create(:budget_heading, group: group) + san_franciso = create(:budget_heading, group: group) + another_heading = create(:budget_heading, group: group) + + new_york_investment = create(:budget_investment, heading: new_york) + san_franciso_investment = create(:budget_investment, heading: san_franciso) + another_investment = create(:budget_investment, heading: san_franciso) + + create(:vote, votable: new_york_investment, voter: user1) + create(:vote, votable: san_franciso_investment, voter: user1) + + expect(user1.headings_voted_within_group(group)).to include(new_york) + expect(user1.headings_voted_within_group(group)).to include(san_franciso) + expect(user1.headings_voted_within_group(group)).to_not include(another_heading) + + expect(user2.headings_voted_within_group(group)).to_not include(new_york) + expect(user2.headings_voted_within_group(group)).to_not include(san_franciso) + expect(user2.headings_voted_within_group(group)).to_not include(another_heading) + end + end + describe "#debate_votes" do let(:user) { create(:user) }