如何在rails中构建一个Poll / Survey类型的应用程序

我正在尝试了解如何在rails中创建民意调查/调查应用程序。

现在我有以下型号:

Poll (id, question:string, answer_1:string, answer_2:string, answer_3:string, answer_4:string, answer_5:string) 

如何跟踪每个用户的PollVote? 此外,我将如何构建显示民意调查的表单,并提供问题和答案。 然后查询PollVote模型以查看用户是否进行了投票?

想法? 谢谢

为了获得最大的灵活性,我将其模型如下:

 class Poll < ActiveRecord::Base has_many :questions has_many :responses, :through => :questions end class Question < ActiveRecord::Base belongs_to :poll has_many :answers has_many :responses, :through => :answers end class Answer < ActiveRecord::Base belongs_to :question has_many :responses end class Response < ActiveRecord::Base belongs_to :user belongs_to :answer end 

然后你可以做以下事情:

 Response.count(:conditions => "question_id = #{@question.id} AND answer_id = #{@answer.id}") 

编辑

延伸我的专业知识的限制,但这里有一些代码,可以让你开始其余的。 不以任何方式进行语法检查或测试。 更能激发灵感。

 class PollsController < ApplicationController ... def show @poll = Poll.find(params[:id], :includes => { :questions => { :answers => :responses } } ) @responses = {} @poll.responses.each do |r| @responses[r.answer.question.id] = r if r.user == current_user end end ... end # in app/views/poll/show.html.haml %ul - @poll.questions.each do |question| %li %p= question.text = form_for (@responses[question.id] || Response.new) do |f| - question.answers.each do |ans| = f.radio_button :answer, ans.id = f.label( ('answer_' << ans.id).to_sym, ans.text ) 

请记住,这可能是最简单但效率最低的方法。 如果您正在处理大量响应,则需要将大量此处理移动到数据库。

另外,请查看此问题以处理响应唯一性。 我的代码旨在让用户每个问题保持一票,但实际上并没有validation这一点。