我有一个像这样简单的AR协会:
Question has_many :answers
Answer belongs_to :question
with
`question_id` int(11) NOT NULL,
`is_accepted` tinyint(1) DEFAULT NULL,
在答案中。我只有一个is_accpeted答案,我想知道是否有一个很容易排序到顶部(只是一个订单)?
THX
编辑: 这是我的答案课:
class Answer < ActiveRecord::Base
belongs_to :question
end
答案 0 :(得分:16)
答案在您的架构中
`is_accepted` tinyint(1)
对于许多数据库,ActiveRecord将布尔值true
和false
存储为1
和0
所以
question = Question.find(23)
questions.answers.order("is_accepted DESC")
应该做你想做的事。
您也可以将其添加为默认订单。
class Question
has_many :answers, :order => "is_accepted DESC" # rails 3
has_many :answers, -> { order "is_accepted DESC" } # rails 4
end
现在question.answers
将始终以“is_accepted”开头。
答案 1 :(得分:2)
在has_one
类
Question
关联
class Question
has_many :answers
has_one :accepted_answer, :class_name => "Answer", :conditions => {:is_accepted => true}
end
class Answer
belongs_to :question
end
现在
q1.answers # returns an array of Answers objects
q1.accepted_answer # returns the accepted answer (if any)
要按接受状态对答案进行排序,请更改关联顺序:
has_many :answers,:order => "is_accepted DESC"
现在
q1.answers # returns the accepted answer on the top