2011-07-25 74 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中实现。