Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Rails, how should I implement a Status field for a Tasks app - integer or enum?
    text
    copied!<p>For a Rails 3.0 Todo app, I have a Tasks model with a <strong>Status</strong> field. What's the best way to store the Status field data (field type) and still display a human-readable version in a view (HTML table)? Status can be: </p> <p>0 = Normal<br> 1 = Active<br> 2 = Completed</p> <p>Right now I have this: </p> <h2>Rails Schema Here:</h2> <blockquote> <p>create_table "tasks", :force => true do |t|<br> t.integer "status", :limit => 1, :default => 0, :null => false</p> </blockquote> <h2>Rails Model Here:</h2> <pre><code>class Task &lt; ActiveRecord::Base validates_inclusion_of :status, :in =&gt; 0..2, :message =&gt; "{{value}} must be 0, 1, or 2" </code></pre> <h2>Rails View Here:</h2> <pre><code>&lt;h1&gt;Listing tasks&lt;/h1&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Status&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; &lt;% @tasks.each do |task| %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= task.status %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= task.name %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= link_to 'Show', task %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= link_to 'Edit', edit_task_path(task) %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= link_to 'Delete', task, :confirm =&gt; 'Are you sure?', :method =&gt; :delete %&gt;&lt;/td&gt; &lt;/tr&gt; &lt;% end %&gt; &lt;/table&gt; </code></pre> <h2>Requirements</h2> <ol> <li><p>Store a Task's status in the db such that the values are easily localizable, i.e. I'm not sure I want to store "normal", "active", "completed" as a string field.</p></li> <li><p>Solution must work with Rails 3.0.</p></li> </ol> <h2>Questions:</h2> <ol> <li><p>Should I store the field as an integer (see above)? If so, how do I display the correct human readable status in an HTML table in my Rails view, e.g. show "Active" instead of "1" in the HTML table.</p></li> <li><p>Should I use an enum? If so, is this easy to localize later?</p></li> <li><p>Should I use straight strings, e.g. "Normal", "Active", "Completed"</p></li> <li><p>Can you provide a quick code sample of the view helper, controller or view code to make this work?</p></li> </ol>
 

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