ruby - Best practice for ordering values in an ActiveRecord database by a 'given value' of string in Rails? -
i'm sure common issue when working databases, i'm trying set activerecord database in rails (although think apply database systems), can order rows based on value assign strings.
for example, i'd order items based on
common less common moderate rare none
i can think of few ways it, each 1 ends seeming little messy. hoping common enough issue there established best-practice going this.
it looks need enum:
enum status: [:none, :rare, :moderate, :less_common, :common]
after have methods item.none?
, item.status #=> none
etc. using enum should create integer
field in table, , each status saved integer none -> 0
, rare -> 1
etc. explicitly map relation between attribute , database integer.
for sorting status in case write:
yourmodel.all.order(:status)
Comments
Post a Comment