ActiveRecord的和关联排序

编程入门 行业动态 更新时间:2024-10-27 05:22:42
本文介绍了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 end

now question.answers will always start with the "is_accepted" first.

更多推荐

ActiveRecord的和关联排序

本文发布于:2023-10-23 19:58:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!