gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中构建投票/调查类型的应用程序

转载 作者:行者123 更新时间:2023-12-01 02:03:58 24 4
gpt4 key购买 nike

我正在尝试了解如何在 Rails 中创建投票/调查应用。

现在我有以下模型:

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

如何跟踪每个用户的 PollVote?另外,我将如何在显示投票的地方构建带有问题和答案的表单。然后查询整个 PollVote 模型以查看用户是否进行了任何投票?

想法?谢谢

最佳答案

为了最大的灵 active ,我会像下面这样建模:

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用于处理响应的唯一性。我的代码旨在让用户对每个问题投一票,但实际上并没有验证这一点。

关于ruby-on-rails - 如何在 Rails 中构建投票/调查类型的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6479130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com