问题描述
||
我正在尝试了解如何在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 )
请记住,这可能是最简单但效率最低的方法。如果您要处理大量响应,则需要将大量处理移至数据库。
另外,请看此问题以处理响应的唯一性。我的代码旨在使用户对每个问题投一票,但实际上并没有对此进行验证。