How to Use Params in Rails: Accessing Request Data Easily
In Rails, you use
params to access data sent by the user through forms, URLs, or API requests. It is a hash-like object available in controllers that holds all request parameters. You can access values by keys like params[:id] or params[:user][:name].Syntax
The params object in Rails is a hash-like structure that stores all parameters from the request. You access values using keys, which can be symbols or strings.
params[:key]- Access a single parameter by key.params[:nested][:key]- Access nested parameters, common with form data.params.to_unsafe_h- Convertparamsto a regular hash if needed.
ruby
def show user_id = params[:id] # Access single param user_name = params[:user][:name] # Access nested param end
Example
This example shows a simple Rails controller action that reads parameters from a URL and a form submission.
ruby
class UsersController < ApplicationController
def show
# Accessing URL parameter :id
@user_id = params[:id]
end
def create
# Accessing nested form parameters
@user_name = params[:user][:name]
@user_email = params[:user][:email]
end
endOutput
When visiting /users/5, @user_id will be "5".
When submitting a form with user[name] and user[email], @user_name and @user_email will hold those values.
Common Pitfalls
Common mistakes when using params include:
- Not checking if nested keys exist, which can cause errors.
- Trusting
paramsblindly without filtering, leading to security risks. - Confusing symbol and string keys.
Always use strong parameters (params.require(...).permit(...)) to whitelist allowed keys in Rails controllers.
ruby
def create # Wrong: trusting all params directly User.create(params[:user]) # Right: using strong parameters User.create(user_params) end def user_params params.require(:user).permit(:name, :email) end
Quick Reference
| Usage | Description |
|---|---|
| params[:id] | Access a single parameter from URL or form |
| params[:user][:name] | Access nested parameter from form data |
| params.require(:user).permit(:name, :email) | Strong parameters to whitelist keys |
| params.to_unsafe_h | Convert params to a regular hash (use carefully) |
Key Takeaways
Use
params in controllers to access request data by keys.Always use strong parameters to whitelist allowed keys for security.
Check for nested keys carefully to avoid errors.
Remember
params is a hash-like object, not a plain hash.Use
params[:key] for simple access and params[:nested][:key] for nested data.