开发者

Showing one table record at a time?

I'm currently creating an app where users have the possibility to create questions for everyone to answer and then users can answer those questions and the app keeps track of those answers for every开发者_StackOverflow single user.

So I have 2 tables "questions" and "answers".

The creating of a question already works, but now I'm kind of stuck at displaying only one question at a time for a user, which he hasn't answered yet and then display the next question he hasn't answered yet.

I hope someone can explain to me how to only show one table record at a time, and then efficiently keep track which of those questions have been answered yet.

Thanks


I think you have the following models:

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

Then in your controller, you can have the following

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

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


Create a attribute "anwsered" in your questions tables (0 = not anwsered, 1 anwsered) And then :

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


You could setup routes such that /question/:id would show the question of that ID. After answering, you can add the person's answer to the answer's table and move onto the next ID.

To make sure a user doesn't answer the same question twice, do a check upon loading each question to make sure the user doesn't already have an answer in the table.


You can implement those as other collections and scopes as follows:

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

And use it follows:

Question.:unanswered_question_for_user(user.answered_questions)

I am assuming that you are using rails 3. The same can be implemented in rails 2.3 also.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜