Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>this code could help you...</p> <p>First, create in the lib folder a file named:</p> <pre><code>integer_to_enum.rb </code></pre> <p>In the file put this code:</p> <pre><code>module IntegerToEnum class &lt;&lt; self def included(klass) klass.extend(ModelClassMethods) end end module ModelClassMethods def fields_to_enum(options={}) class_eval &lt;&lt;-end_eval def set_enum_options @enum_options = #{options.inspect} end end_eval options.each_pair do |k,v| class_eval &lt;&lt;-end_eval def #{k.to_s} self.set_enum_options @enum_options[:#{k.to_s}][read_attribute(:#{k.to_s}).to_i] end def #{k.to_s}=(v) self.set_enum_options unless @enum_options[:#{k.to_s}].include?(v) return false end write_attribute(:#{k.to_s}, @enum_options[:#{k.to_s}].index(v)) @#{k.to_s} end end_eval end end end end </code></pre> <p>On the enviroment.rb, put this at the bottom, after 'end'</p> <pre><code>ActiveRecord::Base.send :include, IntegerToEnum </code></pre> <p>And last, in the model you want to 'translate' the Integer field put:</p> <pre><code>class YourModel &lt; ActiveRecord::Base fields_to_enum :appointment_type =&gt; [:unknown, :medical, :trial], :other_field_type =&gt; [:type_a, :type_b, :type_c] end </code></pre> <p>With this, you could do something like: </p> <pre><code>m = YourModel.find(1) m.appointment_type #=&gt; :unknown m.appointment_type = :trial #=&gt; :trial m.save #=&gt; and this will save with the index value of the array definition, since ':trial' is in the 3er position, the sql resulting will save with this number </code></pre> <p>and that all.. hope to help you</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload