2

当我们在stackoverflow中提问,有人回答你的问题,那么模型关系就是

class Question < ActiveRecord::Base
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
end

你会把一个答案作为你问题的最佳答案,那么关系是

class Question
  has_one answer (the best one)
end

但有时,问题没有最佳答案(例如:未提供答案)

我的问题是如何表达问题和最佳答案之间的关系。

4

2 回答 2

2
$> rails g migration add_best_to_answers best:boolean

> a = Answer.first
> a.best = true
> a.save
> q = a.question 
> q.a.best? # => true
于 2013-02-12T08:03:10.480 回答
1

有点多余的解决方案,但是如果您需要(0..1)使用标准 Rails 关系 DSL 实现多重性,您可以使用through关系:

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
于 2013-02-12T08:27:17.380 回答