开发者

Rails: How to model "question has many answers but only one accepted answer"?

Like on StackOverflow, there is a question and that question has many answers.

But only one of the answers is marked as accepted.

How to implement the same thing in Rails?

The models and tables I have are:

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)

UPDATE (@voldy, thanks! But that doesn't seem to work?)

I added belongs_to :accepted_answer, :class_name => 'Answer' in the Question model. Then added a accepted_answer_id and ran this code:

@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开发者_Go百科!

But the accepted_answer_id field in questions table remains null? I also tried with field name as answer_id, but the same result.


I think there are different approaches. One of them is to add answer_id to questions table:

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

Somewhere in the view if question.accepted_answer == answer etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜