本文介绍了ActiveRecord的和关联排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样一个简单的AR协会:
问题的has_many:答案 答belongs_to的:问题 同 `question_id` INT(11)NOT NULL, `is_accepted` TINYINT(1)DEFAULT NULL,在答案。我只有一个is_accpeted答案,想知道是否有一个简单的排序的顶端(只是一个数量级)?
THX
编辑: 这里是我的回答类:
类答:LT;的ActiveRecord :: Base的 belongs_to的:问题 结束解决方案
答案是在你的架构
`is_accepted` TINYINT(1)
对于很多数据库,ActiveRecord的商店布尔值真和假为 1 和 0
所以
问题= Question.find(23) questions.answers.order(is_accepted DESC)
应该做你想要的。
您还可以添加此为默认顺序。
类问题 的has_many:答案:为了=> is_accepted DESC#导轨3 的has_many:答案 - > {令is_accepted DESC}#导轨4 结束现在 question.answers 将总是以is_accepted之首。
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 endnow question.answers will always start with the "is_accepted" first.
更多推荐
ActiveRecord的和关联排序
发布评论