就像在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
,但结果相同。
答案 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
等。