我试图了解如何在 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}")
Edit:
扩展了我的专业知识的极限,但这里还有一些代码应该可以帮助您开始其余的工作。未以任何方式进行语法检查或测试。灵感比什么都重要。
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 )
请记住,这可能是最简单但效率最低的方法。如果您正在处理大量响应,您将需要将大量处理移至数据库。
另外,看看这个问题 https://stackoverflow.com/questions/6196560/ruby-on-rails-specifying-uniqueness-in-db-across-multiple-columns用于处理响应的唯一性。我的代码旨在让用户对每个问题投一票,但它实际上并没有验证这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)