代码之家  ›  专栏  ›  技术社区  ›  Zabba fl00r

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

  •  1
  • Zabba fl00r  · 技术社区  · 14 年前

    就像StackOverflow一样,有一个问题,这个问题有很多答案。
    但只有一个答案被标记为接受。

    我有的模型和表格是:

    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!
    

    但是 接受回答 字段输入 questions 我也试过用字段名 answer_id ,但结果相同。

    1 回复  |  直到 14 年前
        1
  •  4
  •   Voldy    14 年前

    我认为有不同的方法。其中之一是在问题表中添加答案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 等。