【发布时间】:2010-11-03 22:10:21
【问题描述】:
就像在 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,谢谢!但这似乎不起作用?)
我在 Question 模型中添加了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!
但是questions 表中的accepted_answer_id 字段仍然为空?
我也尝试使用字段名称为answer_id,但结果相同。
【问题讨论】:
-
试试
@question.answer_id = an_answer.id。如果您想使用accepted_answer_id而不是answer_id,请将:foreign_key => "accepted_answer_id"添加到关系中。
标签: ruby-on-rails models