2011-07-25 34 views
0

我目前正在創建一個應用程序,用戶有可能爲每個人創建問題以供回答,然後用戶可以回答這些問題,應用程序會跟蹤每個用戶的答案。一次顯示一張表記錄?

所以我有2個表格「問題」和「答案」。

創建一個問題已經有效,但現在我被困在一次只顯示一個問題的用戶,他還沒有回答,然後顯示他沒有回答的下一個問題然而。

我希望有人能向我解釋如何一次只顯示一張表格記錄,然後有效地跟蹤哪些問題已經被回答。

感謝

回答

1

我覺得你有以下型號:

class Question.. 
    has_many :answers 
end 

class User.. 
    has_many :answers 

    def answered_questions 
    answers.collect {|answer| answer.question} 
    end 

    def unanswered_questions 
    Question.all - answered_questions 
    end 

    def next_unanswered_question 
    unanswered_questions.first 
    end 

end 

class Answer.. 
    belongs_to :question 
    belongs_to :user 
end 

然後在你的控制器中,你可以有以下的

class AnswersController... 
    def new 
    @question = current_user.next_unanswered_question 

    if @question.nil? 
     flash[:notice] = 'You are done!' 
    end 
    end 
end 
+0

「Question.all - answers_questions」 - > RoR太美了:) – emrass

+0

太棒了!非常感謝! – Mexxer

0

創建您的問題表 「anwsered」 一個屬性(0 =不anwsered,1 anwsered) 然後:

 SELECT * FROM questions WHERE anwsered = '0' LIMIT 1 
+0

不是我在找什麼...我想展示那些尚未被特定用戶回答的問題。因此,如果顯示的問題是在某個用戶的回答問題 – Mexxer

+0

的某個地方,那麼如果問題已經得到回答以及哪位用戶回答了問題,則需要進行存儲。如果只有1個用戶可以添加一個問題添加屬性userId,如果超過1個用戶可以回答問題,請創建一個名爲user_anwsers(user_id,anwser_id)的新表。要檢查id = 1的用戶沒有回答哪個問題,請使用SELECT * FROM WHERE answers ='0'和answers_user_id!='1'。這是你在找什麼? – blejzz

0

您可以設置路由,使/ question /:id顯示該ID的問題。回答完畢後,您可以將該人的答案添加到答案表中並移至下一個ID。

要確保用戶不會回答同一問題兩次,請在加載每個問題時進行檢查,以確保用戶在表中沒有答案。

0

您可以實現這些其他收藏品和範圍如下:

class User 
    has_many :answers 
    has_many :answered_questions, :through => :answers, :class_name => 'Question' 
end 

class Question 
    scope :unanswered_question_for_user, lambda { |answered_questions| where ("id not in (?)",answered_questions).limit(1) 
end 

class Answer 
    belongs_to :question 
    belongs_to :user 
end 

並以此如下:

Question.:unanswered_question_for_user(user.answered_questions)

我假設你正在使用的軌道3.同樣可以也可以在rails 2.3中實現。