Doubt about float field query (ruby on Rails with mysql)

Asked

Viewed 174 times

4

Hello, I have a question regarding the database with Rails.

If I declare a field to be "float", when I do the query, I need to use the ". to_float" so that Rails understands 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
     

  • It depends on how you stated it when you generated the Model. Whether you made a rails generate scaffold ProAttr pro_id:integer aggregate_effort:float, it will understand that it is a float. Otherwise you will have to call the to_float method.

  • hmm, I got it, so that’s why hehe, I always create direct tables without the scaffold, thanks for the clarifications!

  • You can create the table directly as well. But for use of the framework it is interesting you give at least one rails generate model Model attr1:type1 attr2:type2 --no-migration, so --no-Migration prevents you from creating a new table by giving the db:migrate

1 answer

2


The Rails works with point fields flutuante de modo transparent, so you don’t need to make this conversion explicit. A detail, for migrations from Rails pontos flutuantes are worked in a generic way such as decimal.

Creation of 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 precision and scale.

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

To generate already with these modifiers would look like this

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

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.