Reputation: 1374
Let's say I have the following select boxes in my form for a Gate
object:
f.select(:type_use, options_for_select([['Enter & Exit', 8],
['Only Enter', 4],
['Only Exit', 4],
['Only Enter for visitors', 2],
['Only Exit for visitors', 2]],
@gate.type_use),
{ :include_blank => '- select -' },
{ :class => 'form-control'})
These options will never change. The integers like 4 and 8 represent the number of cycles per day, and I later use these integers to do calculations. However I still want to retain the correct string labels for each integer for use in my view, so i can show that a gate has an 'Only Exit' type of use, for example.
So, is it possible to save select options as a hash, or does Rails have some other way to map integers to strings for use in my application?
Previously what i've been doing is just saving the string values, and then using if
statements, manually assigning to a variable the corresponding integer based on the string value, before doing calculations. But I have yet to discover a more efficient and elegant way to do this.
In my research I did find information about Enums, but I don't think it applies to this situation because I have duplicate integers and Enums seem more like sequential indexes to me. Also it seems that other questions about hashes in select boxes have revolved around populating options for select with a hash, rather than saving as a hash
Upvotes: 1
Views: 87
Reputation: 4404
You can save Hash
and Array
by using Serialize on the Model
you want to save the Hash
or Array
Ex:
class User < Active::Record
serialize :data, Hash # for hash
serialize :other_data, Array # for array
end
There is also a DataType
called hstore
in postgres that allows you to save Hash
data and then be able to perform searches and index items in the Hash
To use it you first have to enable the hstore
extension and then use it in your migrations
.... add_column :data_set, :hstore, default: {}
Upvotes: 1