19
loading...
This website collects cookies to deliver better user experience
# songs_controller.rb
patch "/songs:id" do
song = Song.find(params[:id])
attrs_to_update = params.select{|k,v| ["name", "genre"].include?(k)}
song.update(attrs_to_update)
song.to_json
end
params
may seem a bit magical as it somehow automatically contains the data included in requests:params = {
"name" => "some_name",
"genre" => "some_genre",
"id" => "some_id"
}
params
?ActionController::Base
that accesses the parameters passed from a request and returns a hash that encapsulates the parameters. It can access those parameters in one of two main ways: through the request body or through the request path. // A POST request that contains a body object
const newSong = {
name: "Fly Me to the Moon",
genre: "Jazz"
}
const configObj = {
method: "POST",
headers: {
"Content-Type": "applications/json",
"Accept": "applications/json"
},
body: JSON.stringify(newSong)
};
fetch("http://example.com/songs", configObj);
params
hash:params = {
"name" => "Fly Me to the Moon",
"genre" => "Jazz"
}
Note: The keys and values of a params
hash will always be of the string type. However, the hash keys can be accessed indiscriminately as strings or symbols since params
doesn't actually return a hash, but it returns something similar called Sinatra::IndifferentHash
.
params
hash based on those attributes. This allows us to design routes more dynamically instead of hard-coding each route individually. There are two types of parameters that can be accessed based on the URL attributes: query and route parameters.?
in the request URL as shown below:// A GET request with query parameters in the URL
fetch(http://www.example.com/songs?name=foo&genre=pop)
# songs_controller.rb
get "/songs" do
...
end
params
hash will still include the query parameters found in the request path:params = {
"name" => "foo",
"genre" => "pop"
}
params
hash:# songs_controller.rb
get "/songs/:id" do
...
end
fetch("http://www.example.com/songs/3")
params
hash:params = { "id" => "3" }
fetch("http://www.example.com/songs/3?name=foo&genre=pop")
params
hash:params = {
"id" => "3",
"name" => "foo",
"genre" => "pop"
}
params
is often unquestioned and left to wonders, its behavior under-the-hood is actually straightforward to grasp. To summarize, params
is an inherited method that returns a hash that contains parameters passed by a request through its body or through its URL. Overall, understanding this behavior will (hopefully) make your life easier by equipping you with the ability to control the structure of the params
hash as well as build routes more effectively.