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

时间:2011-06-25 16:44:41

标签: ruby-on-rails ruby-on-rails-3

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

现在我有以下型号:

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

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

想法?感谢

1 个答案:

答案 0 :(得分:5)

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

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 )

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

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