I have a model named, Measurable, that stores many different types of of 
measurements for different things.  All the measurements can be represented 
as a decimal, so my value column is of datatype decimal.  My users though 
wish to view and input these value is either integers or mixed numbers (ex: 
31 1/8) as well, depending on the measurable_type.  Right now I'm able to 
convert the mixed number to a decimal value and store it into my database 
as a proper decimal. But I'm trying to figure out how to convert it from a 
decimal value to the mixed number I'm wanting to show the user in my form, 
so they can make edits if necessary.  Below I have the setter method I 
made, but my attempts at creating a proper getter haven't work.  I'm not 
really sure how to go about it.

class Measurable < ActiveRecord::Base

  # columns: id, unit_id, measurable_type_id, reliability_id, value, 
created_at, updated_at

  belongs_to :measurable_type

  def value=(value)
    # Has more than one value
    if value.split(" ").size > 1
      values = value.to_s.strip.split(" ") # split the mixed number to 
whole number and fraction for conversion preparation
      if values.size > 1
        # a whole number and fraction was supplied
        whole_number = values.first.to_i
        fraction     = values.last

        numerator    = values.last.split("/").first.to_d
        denominator  = values.last.split("/").last.to_d

        value = whole_number + (numerator / denominator)
     else
       # a fraction wasn't specified
       whole_number = values.first
       value = whole_number
     end
    end

    @value = value
    super
  end

end


-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/a1239c91-e598-40ad-9472-60bbfec44b23%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to