我目前正在創建一個應用程序,用戶有可能爲每個人創建問題以供回答,然後用戶可以回答這些問題,應用程序會跟蹤每個用戶的答案。一次顯示一張表記錄?
所以我有2個表格「問題」和「答案」。
創建一個問題已經有效,但現在我被困在一次只顯示一個問題的用戶,他還沒有回答,然後顯示他沒有回答的下一個問題然而。
我希望有人能向我解釋如何一次只顯示一張表格記錄,然後有效地跟蹤哪些問題已經被回答。
感謝
我目前正在創建一個應用程序,用戶有可能爲每個人創建問題以供回答,然後用戶可以回答這些問題,應用程序會跟蹤每個用戶的答案。一次顯示一張表記錄?
所以我有2個表格「問題」和「答案」。
創建一個問題已經有效,但現在我被困在一次只顯示一個問題的用戶,他還沒有回答,然後顯示他沒有回答的下一個問題然而。
我希望有人能向我解釋如何一次只顯示一張表格記錄,然後有效地跟蹤哪些問題已經被回答。
感謝
我覺得你有以下型號:
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
創建您的問題表 「anwsered」 一個屬性(0 =不anwsered,1 anwsered) 然後:
SELECT * FROM questions WHERE anwsered = '0' LIMIT 1
您可以設置路由,使/ question /:id顯示該ID的問題。回答完畢後,您可以將該人的答案添加到答案表中並移至下一個ID。
要確保用戶不會回答同一問題兩次,請在加載每個問題時進行檢查,以確保用戶在表中沒有答案。
您可以實現這些其他收藏品和範圍如下:
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中實現。
「Question.all - answers_questions」 - > RoR太美了:) – emrass
太棒了!非常感謝! – Mexxer