Controllers Should Convert Parameters to Richer Types
Understand how to handle parameter conversion in Rails controllers by transforming string inputs from HTTP into appropriate types. Learn why controllers shield the business logic from raw strings and how to manage type conversions effectively, balancing Active Record conveniences with custom needs.
We'll cover the following...
Active Record handling
As the invokers of business logic, controllers are responsible for converting parameters into properly typed objects:
def show
@widget = Widget.find(params[:id])
end
This code takes a string containing an identifier that we assume identifies a widget and looks it up in the database, passing the actual widget to the view. Because HTTP is a text-based protocol, and because Rails provides us only hashes of strings as an API into it, controllers are in the unique position to insulate the rest of the codebase from this ...