2011-06-25 9 views
3

私は投票/アンケートアプリをレールに作成する方法を理解しようとしています。私は、ユーザーごとにPollVoteを追跡するにはどうすればよいポール/アンケートタイプのアプリをレールに組み込む方法

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

今私は、次のモデルがありますか?また、どのように私はそれが質問と回答(s)と投票を表示するフォームを構築するだろう。そして、ユーザーが投票したかどうかを確認するためにPollVoteモデルを照会しますか?

アイデア?

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

編集

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 

次に、あなたのようなことを行うことができます:ストレッチ

おかげ

答えて

5

は、私はそれを最大限の柔軟性のために、以下のようなものをモデル化したいです私の専門知識の限界ですが、ここでは残りの部分を始めるためのコードがいくつかあります。構文チェックやテストは一切行いません。他の何よりもインスピレーションを求めること。

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を参照してください。私のコードは、ユーザーを質問ごとに1つの投票に保つように設計されていますが、実際には検証しません。

+0

ありがとうございましたが、特定の回答に投票した場合、質問、回答、ユーザーのフォームを表示するにはどうすればよいですか。それは表示する必要があります。彼らはまた、1つの質問につき1つの投票だけで、投票を変更することができます。アイデア? – AnApprentice

+0

@AnApprentice私はいくつかのコードを追加して、実行可能な方法を示しました。あなたの考えを見てください。 – Luke

+1

google for "rails counter_cache" ...これは、投票ごとの質問数、質問ごとの回答数、回答ごとの回答数などの高速クエリで役立ちます –

関連する問題