[Ruby on Rails (RoR)] Best practices about Rails Action Controller Overview

Best practices about Rails Action Controller Overview

In this guide you will learn what is the best practices about controllers work and how they fit into the request cycle in your application.

ActionDispatch::Request

Get url, path, fullpath from request.

1
2
3
4
5
6
7
8
9
10
11
# Full path with query string
>> request.url
=> "http://localhost:3000/ask-help.amp?hui=pizda"

# Virtual path without query string
>> request.path
=> "/ask-help.amp"

# Virtual path with query string
>> request.fullpath
=> "/ask-help.amp?hui=pizda"

Pass arrays & objects via querystring

Rails has some great patterns for passing complex objects via querystring.

Arrays

1
2
3
4
# QueryString: numbers[]=1&numbers[]=2&numbers[]=3
# rails
params[:numbers]
# Output: [1, 2, 3]

Objects

1
2
3
4
5
6
7
8
# QueryString: user[id]=1&user[name]=Nathan
# rails
params[:user]
# Output:
# {
# id: 1,
# name: "Nathan"
# }

Complex Objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# QueryString: users[][id]=1&users[][name]=Nathan&users[][id]=2&users[][name]=Emma
# rails
params[:users]
# Output:
# {
# users: [
# {
# id: 1,
# name: "Nathan"
# },
# {
# id: 2,
# name: "Emma"
# }
# ]
# }

Try It

You can try all this out yourself from a Rails console.

1
2
3
4
# rails c
data = { numbers: [1,2,3] }
CGI.unescape data.to_query
# Output: numbers[]=1&numbers[]=2&numbers[]=3

See more to Pass arrays & objects via querystring the Rack/Rails way (Example)

More to see Ruby on Rails API - ActionDispatch::Request

References

[1] Action Controller Overview — Ruby on Rails Guides - https://guides.rubyonrails.org/action_controller_overview.html

[2] Rails 5 Routing Cookbook: 10 recipes for the novice Rails developer and beyond | by Rui Freitas | Light the Fuse and Run | Medium- https://medium.com/lightthefuse/rails-5-routes-cookbook-10-recipes-for-the-novice-rails-developer-and-beyond-9986f43064bc