我目前正在创建一个应用程序,用户有可能为每个人创建问题以供回答,然后用户可以回答这些问题,应用程序会跟踪每个用户的答案。一次显示一张表记录?
所以我有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