ActiveRecord and association sorting

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 will have only one is_accpeted answer, and I wonder if there is a simple sort in it (only order)?

THX

Edit: here is my answer class:

 class Answer < ActiveRecord::Base belongs_to :question end 
+4
source share
2 answers

the answer in your circuit

 `is_accepted` tinyint(1) 

For many databases, ActiveRecord stores the boolean values 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 always starts with "is_accepted" first.

+16
source

Add has_one association in 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 according to the accepted status, change the order of your association:

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

Now

 q1.answers # returns the accepted answer on the top 
+2
source

All Articles