ActiveRecord和关联排序

时间:2011-09-11 01:07:06

标签: ruby-on-rails activerecord

我有一个像这样简单的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 

2 个答案:

答案 0 :(得分:16)

答案在您的架构中

`is_accepted` tinyint(1)

对于许多数据库,ActiveRecord将布尔值truefalse存储为10

所以

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