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.
Add a comment
|
1 Answer
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.