1

I wanted to know whether you have to convert or cast certain query string or post params to specific data types in order to use them in controllers. For example, if I pass a categoryid (an integer in the database) query string parameter into a controller, do I have to convert it to an integer in my controller using the to_i method or does Ruby do this automatically? Also, how do I test query string param values and their data types using the rails console? I can't really tell what's going on with query string or post params as I test my app.

1 Answer 1

2

Rails (and particularly ActiveRecord) is, in general, relatively tolerant of the datatypes passed. For example, both of these lines will return the User with ID 1:

User.find(1)
User.find('1')

And the same goes for more complex queries:

User.where({ id: '1' })
User.where('id = ?', '1')

Parameters come through to the controller as strings, which means you can just call User.find(params[:id]), without having to call params[:id].to_i.

If you want to inspect the class of a variable in the Rails console, then you can call .class on an object. For example:

[1] pry(main)> "1".class
=> String
[2] pry(main)> 1.class
=> Fixnum

I hope that helps.

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

Comments

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.