Rails: Sort by state in database

Given that I have a house model and it lives through several states, something like this: Dreaming β€”> Planning β€”> Building β€”> Living β€”> Tearing down

If I wanted to get, say, ten houses from the database and sort them by state field, I would first get all the houses in the Building state, then Dreaming , then Living , ...

Is it possible to get all the houses from the database and arrange them according to the state in the order intended before they were extracted? Meaning, at first everyone at home is in a Dreaming state, then Planning , etc., for example. by providing order in an array to compare varieties.

I would like to avoid this in ruby ​​after having selected all the records, and also would not want to use identifiers for states.

UPDATE

After reading on enum implementations, I think if I can get it to work, I will try to combine the enum column plugin using the state_machine plugin to achieve what I need. If someone had done something similar before (especially the combination under Rails 3), I would be grateful for the input!

+4
source share
3 answers

Here is some information on how to use SQL ENUM in rails - they are relatively portable and do something you want - http://www.snowgiraffe.com/tech/311/enumeration-columns-with-rails/

+3
source

If you are using MySQL, then the solution should execute ORDER BY FIELD (state, "Construction", "Dream", "Live", ...):

 House.order("FIELD(state, 'Building', 'Dreaming', 'Living', ...)") 
+3
source

If you want to order a collection according to certain criteria, you must save these criteria somewhere.

I don’t know if this goes against your non-Ruby criteria, but I would probably do something like this:

 class House < ActiveRecord::Base STATES { 0 => "Dreaming", 1 => "Planning", 2 => "Building", 3 => "Living", 4 => "Tearing Down" } validates_inclusion_of :state, :in => STATES.keys def state_name STATES[self.state] end end @houses = House.order("state") 

In this case, the state of the db field is an integer instead of a string. This makes it very efficient for database storage as well as for queries.

Then in your view, you call state_name to get the correct name from the STATES hash stored in the model. You can also change this to use i18n localization using labels instead of hash strings.

+2
source

Source: https://habr.com/ru/post/1337105/


All Articles