Thursday, August 11, 2011

Adding two columns in a table with Rails

I figured out a way to calculate totals from two different columns in a table, but I'm having trouble extracting that logic and moving it out of my view. In this case, an Initiative's total is the sume of the Dexterity and Miscellaneous modifiers. Here's the code I've got so far:

Initiative Total:
<%= (@initiative.dex + @initiative.misc) %>

Pretty easy, right? But I'd like to just call this something like init_total and call it that way, but I'm not quite sure how to write that code. Also, does it matter if I throw a .to_s on the end of this? I noticed it displays the same either way, but I don't know if a .to_s is strictly required. I'm guessing since this information is already a string, converting it to a string is redundant.

Just a quick update. Feels good to be making daily progress on Manticore, especially since I spent a long time spinning my wheels.


  1. Try this:
    class Initiative < ActiveRecord::Base
    # ...
    def total
    dex + misc
    end # => dex + misc

    to_s is automatically called by <%= %>.

  2. Aha, I knew it'd be something simple like that. Awesome!

    I figured out count wasn't what I wanted, after I finally got it to work. Any potential shortcomings to using this method as opposed to the one you showed me a while back? I'll be using this total method for several different models, and each will work similar to this, though they'll have more integers to be added.

  3. This one is specific, explicit, and obvious. The other one is general, implicit, and much more complex, but it should work on ALL models that behave like these do.

    It's programming, you have to choose your own poison :)

  4. Yeah, the complexity of the method you showed me is part of the reason I went looking for a simpler method. I already knew there's more than one way of doing things with Ruby and here we are!