Rails:如何建模“问题有很多答案,但只有一个被接受的答案”?

时间:2010-11-03 22:10:21

标签: ruby-on-rails models

就像在StackOverflow上一样,有一个问题,这个问题有很多答案 但只有一个答案被标记为已被接受 如何在Rails中实现相同的东西?

我拥有的模型和表格是:

class Question < ActiveRecord::Base
    has_many :answers
    has_one :accepted_answer # how to get this to work?
end
#Table: questions(id,question_text)

class Answer < ActiveRecord::Base
    belongs_to :question
end
#Table: answers(id, question_id)

更新(@voldy,谢谢!但这似乎不起作用?)

我在问题模型中添加了belongs_to :accepted_answer, :class_name => 'Answer'。 然后添加了accepted_answer_id并运行此代码:

@question = current_user.questions.find(3)
an_answer = Answer.find(1) #presuming this is the answer i want to accept
@question.accepted_answer = an_answer
@question.save!

accepted_answer_id表中的questions字段仍然为空? 我也尝试使用字段名称answer_id,但结果相同。

1 个答案:

答案 0 :(得分:4)

我认为有不同的方法。其中之一是将answer_id添加到问题表中:

class Question < ActiveRecord::Base
    has_many :answers
    belongs_to :accepted_answer, :class_name => "Answer", 
                                 :foreign_key => :answer_id
end

class Answer < ActiveRecord::Base
    belongs_to :question
end

视图中的某处if question.accepted_answer == answer等。