Doubt regarding float field query (ruby on rails with mysql)

Posted on

Question :

Hello, I have a question regarding a database with rails.

If I declare a field is “float”, when I do the query, do I need to use “.to_float” for the rails to understand the type of this field?

For example, in this calculation:

def self.tipe(a)
  pro = ProAttr.where(:pro_id => pro.id).first

  percent_completed_calculated_aggregate = (pro.aggregate_effort.to_float / pro.to_float) * 100
     

    

Answer :

Rails works with fields with% point of% transparent, so you do not need to do this explicit conversion. A detail for Rails flutuante de modo migrations are worked generically as pontos flutuantes .

Creating the model would look something like:

rails g model ProAttr aggregate_effort:decimal

For this type of field there are extra options ( type modifiers ) as decimal and precision .

Where scale is the total digits that your decimal can have and precision is the number amount after the decimal point (point in this case).

To generate with these modifiers already would be like this

rails g model ProAttr 'aggregate_effort:decimal{5,2}'

If you need to add a decimal field in the migration, something like this:

add_column :pro_attrs, :aggregate_effort, :decimal, precision: 5, scale: 2

Doing so will get you less headache with floating point fields.

    

Leave a Reply

Your email address will not be published. Required fields are marked *