开发者

ActiveRecord and sorting on association

开发者 https://www.devze.com 2023-04-04 13:52 出处:网络
I have a simple AR association like this: Questionhas_many :answers Answerbelongs_to :question with `question_id` int(11) NOT NULL,

I have a simple AR association like this:

Question    has_many :answers

Answer      belongs_to :question

with
  `question_id` int(11) NOT NULL,
  `is_accepted` tinyint(1) DEFAULT NULL,

in the answer. I'll have only one is_accpeted answer and am wondering if there is an easy to sort that to the top (just an order by)?

thx

Edit: here is m开发者_JAVA技巧y Answer class:

class Answer < ActiveRecord::Base
    belongs_to :question 
end 


the answer is in your schema

`is_accepted` tinyint(1)

For many databases, ActiveRecord stores booleans true and false as 1 and 0

so

question = Question.find(23)
questions.answers.order("is_accepted DESC")

should do what you want.

You can also add this as the default order.

class Question
  has_many :answers, :order => "is_accepted DESC" # rails 3
  has_many :answers, -> { order "is_accepted DESC" } # rails 4
end

now question.answers will always start with the "is_accepted" first.


Add a has_one association on the Question class

class Question
  has_many :answers
  has_one  :accepted_answer, :class_name => "Answer", :conditions => {:is_accepted => true}
end

class Answer
  belongs_to :question
end

Now

q1.answers # returns an array of Answers objects
q1.accepted_answer # returns the accepted answer (if any)

To sort the answers by accepted status change your association order:

has_many :answers,:order => "is_accepted DESC"

Now

q1.answers # returns the accepted answer on the top
0

精彩评论

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