【问题标题】:Rails: How to model "question has many answers but only one accepted answer"?Rails:如何建模“问题有很多答案但只有一个接受的答案”?
【发布时间】: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 =&gt; '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 =&gt; "accepted_answer_id" 添加到关系中。

标签: ruby-on-rails models


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答,我试过了,但它似乎不起作用?请查看我的问题的更新
  • 我已将:foreign_key 添加到关系中。另请参阅我对您的问题的评论。如果你使用它,你应该将这个新字段添加到attr_accessible(我鼓励使用它)。
  • 太棒了!添加foreign_key 就可以了。一个问题:不会让字段attr_accessible 暴露风险:有人可以通过控制器发送参数来更改接受的答案?
  • 你是对的!对我来说,这是一个午夜。不要使用此字段:)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
相关资源
最近更新 更多