Reputation: 106
When we ask question in stackoverflow, and somebody answer your question, then the model relationship will be
class Question < ActiveRecord::Base
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
end
you will take one answer as the best answer of your question, then the relationship is
class Question
has_one answer (the best one)
end
but sometimes, question hasn't best answer (such as: no answer is provided)
my question is how to express the relationship between Question an BEST answer.
Upvotes: 1
Views: 204
Reputation: 121010
A bit superfluous solution, but if you need to implement (0..1)
multiplicity with standard rails relationship DSL, you may use through
relation:
class Question < ActiveRecord::Base
has_many :answers
has_one :answer, :through => :bestanswers
end
class Answer < ActiveRecord::Base
belongs_to :question
has_one :bestanswer
end
class BestAnswer < Answer
belongs_to :answer
belongs_to :question
end
Upvotes: 1
Reputation: 17949
$> rails g migration add_best_to_answers best:boolean
> a = Answer.first
> a.best = true
> a.save
> q = a.question
> q.a.best? # => true
Upvotes: 2