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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With