Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord and sorting on association

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 my Answer class:

class Answer < ActiveRecord::Base
    belongs_to :question 
end 
like image 833
timpone Avatar asked Dec 02 '22 01:12

timpone


2 Answers

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.

like image 129
Matthew Rudy Avatar answered Dec 04 '22 10:12

Matthew Rudy


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
like image 36
Harish Shetty Avatar answered Dec 04 '22 09:12

Harish Shetty