Note that there are some explanatory texts on larger screens.

plurals
  1. POValidating a Model Property is Greater than Another
    primarykey
    data
    text
    <p>First, let me say I am <em>extremely</em> new to Rails (toyed with it a time or two but forcing myself to write a complete project with it now, started on it yesterday).</p> <p>I am now trying to validate that a model property (terminology?) is greater than another. This appeared to be a perfect instance for <code>validates_numericality_of</code> with the <code>greater_than</code> option, but alas that throws an error telling me <code>greater_than expects a number, not a symbol</code>. If I try to typecast that symbol <code>.to_f</code> I get an <code>undefined method</code> error.</p> <p>Here is what I eventually did and I am curious as to whether there is a better way. It's just a simple system to control project releases, we only have major/minor releases (one-dot) so float felt like the right decision here.</p> <pre><code>class Project &lt; ActiveRecord::Base validates_numericality_of :current_release validates_numericality_of :next_release validate :next_release_is_greater def next_release_is_greater errors.add_to_base("Next release must be greater than current release") unless next_release.to_f &gt; current_release.to_f end end </code></pre> <p>This works - it passes the relevant unit test (below for your viewing pleasure), I'm just curious as to if there is an easier way - something I could have tried otherwise.</p> <p>Relevant unit test:</p> <pre><code># Fixture data: # PALS: # name: PALS # description: This is the PALS project # current_release: 1.0 # next_release: 2.0 # project_category: 1 # user: 1 def test_release_is_future project = Project.first(:conditions =&gt; {:name =&gt; 'PALS'}) project.current_release = 10.0 assert !project.save project.current_release = 1.0 assert project.save end </code></pre>
    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.
 

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