5

I have a RoR + MySQL setup. In the database there is a Tinyint field t. When I read the value of t from Rails I get true or false because a Tinyint field is interpreted by Rails as boolean. So far so good.

How do I read this field t as an actual integer from Rails?

2
  • 1
    Please show the code you are using to read it as a boolean; I'm surprised that you can't read it as an integer in the same way (it is, after all, a 1-byte integer column). I don't know if there's a better way in Ruby, but at worst you could try SELECT CONVERT(tinyintcolumn, [UN]SIGNED) FROM my_table? Commented Aug 30, 2012 at 13:21
  • I just use a standard Model.find_by_id() to fetch the record. Commented Aug 30, 2012 at 13:28

2 Answers 2

7

http://apidock.com/rails/ActiveRecord/AttributeMethods/BeforeTypeCast/attributes_before_type_cast

for instance:

Model.first.attributes_before_type_cast['your_boolean_field']

It depends on your DB what value will be returned, in postgesql it is 'f' or 't'

Sign up to request clarification or add additional context in comments.

2 Comments

If you only need one field, you can also use the method read_attribute_before_type_cast('your_boolean_field') or even your_boolean_field_before_type_cast.
read_attribute_before_type_cast doesn't worked for me. Here, you can see how I resolve it.
2

To build on @sumskyi's response, if you always access this field as a regular integer, you can just override the model's built-in method and save yourself the repetitive motion injury:

class GroceryStore < ActiveRecord::Base
  # rating is a TINYINT column
  # we just redefine the method here to return the value cast how we want it
  def rating
    self.attributes_before_type_cast['rating'].to_i
  end
end

Now if you call grocerystore.rating you'll get an integer instead of a boolean.

1 Comment

Found some more helpful info here: You can disabled boolean interpretation altogether by setting ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans = false in config/application.rb. However, they don't mention that you also have to explicitly require active_record/connection_adapters/mysql2_adapter in application.rb, so make sure not to miss that! See this post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.