简体   繁体   English

Rails中的数据库排序默认值

[英]Database Sorting Defaults in Rails

I'm finishing up my rails app, and I notice that the some of my selects don't have the selection options in order. 我正在完成Rails应用程序,我注意到我的一些选择没有按顺序排列选择选项。 I'm guessing that the ones that do come out right, it's simply that I inserted the values in alphabetical order. 我猜想那些确实正确,只是我按字母顺序插入了值。 Anyway, no surprise that they're not in alpha order, and not really that hard to fix. 无论如何,它们不是按字母顺序排列也不是那么难解决,这不足为奇。

My question is really about the best approach to ensuring the sort order. 我的问题确实是关于确保排序顺序的最佳方法。 I think I read recently that rails (don't know why it would not depend on the database, so not sure I have this right) will pull the items in the order that they were inserted the database. 我想我最近读过,Rails(不知道为什么它不依赖于数据库,所以不确定我是否拥有此权利)将按插入数据库的顺序拉出项目。

If that's is true, is it worth keeping the items in the "default" (the order you want) order and possibly even not forcing an order on the "pull"? 如果是这样,是否值得将项目保持在“默认”(您想要的顺序)顺序中,甚至可能不强制在“拉”上执行顺序? I would think that if for many (at least in my application) cases, it would make sense to "re-sort" the order after each insert, essentially changing the original insert order. 我认为,如果对于很多情况(至少在我的应用程序中),在每次插入后对顺序进行“重新排序”是有意义的,本质上可以更改原始的插入顺序。 That way, whether you're calling the re-sort the order, it will be faster. 这样,无论您是调用重新排序顺序,它都将更快。

Does this even make sense? 这有道理吗? Can you tell a database to "re-sort" the items in the manner discussed? 您能否告诉数据库以讨论的方式对项目进行“重新排序”? Thoughts? 思考?

Thanks. 谢谢。

The order in which postgresql returns the records is unspecified. 未指定postgresql返回记录的顺序。 (see http://www.postgresql.org/docs/9.1/static/queries-order.html ). (请参阅http://www.postgresql.org/docs/9.1/static/queries-order.html )。 You can add a default sort order though to your model, using default_scope. 您可以使用default_scope将默认排序顺序添加到模型中。 Eg 例如

default_scope order('created_at DESC')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM