我正在创建一个投票应用。我正在根据我的需要修改https://www.sitepoint.com/polling-users-rails/。
用户回答民意调查并显示结果。
polls
t.string :question
t.text :description
t.references :division, foreign_key: true
t.date :open_date
t.date :close_date
vote_options
t.string :title
t.references :poll, foreign_key: true
votes
t.references :user, foreign_key: true
t.references :vote_option, foreign_key: true
users
t.string :email
t.decimal :vote_weight
user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :votes, dependent: :destroy
has_many :vote_options, through: :votes
def voted_for?(poll)
vote_options.any? {|v| v.poll == poll }
end
end
vote_option.rb
class VoteOption < ApplicationRecord
belongs_to :poll
validates :question, presence: true
has_many :users,
has_many :votes, dependent: :destroy
def get_vote_count
VoteOption.joins(:votes).joins(:users).where(id: self.id).sum(:vote_weight)
end
end
vote.rb
class Vote < ApplicationRecord
belongs_to :user
belongs_to :vote_option
end
poll.helper
def visualize_votes_for(option)
content_tag :div, class: 'progress' do
content_tag :div, class: 'progress-bar',
style: "width: #{option.poll.normalized_votes_for(option)}%" do
"#{option.votes.count}"
end
visualize_votes_for显示每个选项的总投票数。目前,它为每个值考虑1并计算每个选项的总数。
我希望能够为每个用户设置一个vote_weight,这样就可以计算用户表中vote_weight列中指定的值而不是1。
我试过了:
"#{sum(option.votes.user.vote_weight)}"
但它返回:
undefined method `user' for #<ActiveRecord::Associations::CollectionProxy []>
我做错了什么?
答案 0 :(得分:2)
option.votes
将返回votes
的有效记录集合。请注意,它将是一个集合,而不是一个对象。因此,对集合调用方法user
将不起作用,因为投票属于用户。因此,user
方法只能在vote
对象的实例上调用,而不能在集合上调用。
您可以在VoteOption Model
get_vote_count
def get_vote_count
Vote.joins(:vote_option).joins(:user).where("vote_options.id = #{self.id}").sum(:vote_weight)` # Adjust singularity/plurality of objects as per the requirement
end
并且在option.get_vote_count
等选项对象的视图中使用此方法。