B
B
Bogdan2017-07-30 18:24:24
Ruby on Rails
Bogdan, 2017-07-30 18:24:24

ActiveRecord changing field type?

Hello. I have a table Branch -> code {11}. The value is '0000000001'. For some reason, ActiveRecord converts the field from character to numeric, and here leading zeros are important.

inst = Institution.joins( :branch ).select( 'branches.code' ).first
puts inst.code # 1 
puts inst.class # FixNum

Please tell me how to solve this problem, thanks.
As far as I understand, this is due to the fact that I have a code:integer field in the Institutions table. That's probably why ActiveRecord takes its type. For example, if you rename the field and do
Institution.joins( :branch ).select( 'branches.code as code_branch' ).first

Then everything is fine, but I need exactly the code so that they do not deviate from the writing style. Of course, you can still go and write a less efficient query in terms of performance
Branch.joins( :institutions ).select( :code )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2017-07-31
@2ord

You have an integer type field, but you enter a string value?!
The framework does the conversion itself like this:

code = '0000000001' # строка с числовым значением
puts Integer(code).inspect

For numeric values, leading zeros don't matter, so there's no point in displaying them.
0001, 01, 00000000001, 1 are the same number.
For example, if you need to store a product barcode, then you need to set the string type to the code field.
Then it is the string that will be stored in the database, and not the value converted to an integer.
To work with bit values ​​in integers, use the notation
code = 0b0000000011 # (число 3, включены 0-й и 1-й биты)
puts code.inspect

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question