ActiveRecord and sorting on association

我是研究僧i 提交于 2019-12-10 17:08:06

问题


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 

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7375680/activerecord-and-sorting-on-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!