DEV Community

Angela Lam
Angela Lam

Posted on

Understanding Params In Sinatra

Params?

For my second project at Flatiron, I had to create an MVC Sinatra application. My project was a simple weightlifting tracker where users can log their workouts with exercises and weights. The user creates new workout and exercises by filling out forms, the information from the forms are necessary for me to create my objects in my application. Throughout building my application, one thing I had to test and work with was params. After the user fills out the forms on the site, I had to grab the information from the params hash. I constantly had to go into pry to see what my params was returning to make sure my code was grabbing the correct information.

What is params? Params is short for the word parameter. A parameter a hash that stores key-value pairs that is encoded in a HTTP request. Params comes from ActionController::Base, which is accessed by your application via ApplicationController. Specifically, params refers to the parameters being passed to the controller via a GET or POST request. Params is a method that returns an ActionController::Parameter object that behaves like a hash. It is a way to pass data that goes through our URL and routes. You can call params to access form and URL query data. One thing to note is that the values of a params hash are always a string, even if submitted as an integer. If a field is left blank you'll get an empty string.

How do we pass parameters in Sinatra? I will be focusing on two methods; through a form and dynamic parameters in the URL.

Form Parameters

When data comes through a form, it is an HTML form which is filled by the user. This is known as POST data because it is sent as part of an HTTP POST request. The params hash is not limited to one-dimensional keys and values. It can contain nested arrays and hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:

<form action="/student" method="post">
  Student Name: <input type="text" name="student[name]">
  Student Grade: <input type="text" name="student[grade]">
  Course Name: <input type="text" name="student[course][name]">
  Course Topic: <input type="text" name="student[course][topic]">
  <input type="submit">
</form>
Enter fullscreen mode Exit fullscreen mode

The form above, takes in four inputs from the user. The name attribute in the form build the params hash. After filling out the form and submitting the information, the information will fill your params hash.

params = {
  "student" => {
    "name" => "Joe",
    "grade" => "9",
    "course" => {
      "name" => "US History",
      "topic" => "History"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Below are methods to accessing the values in the params.

params["student"]["name"] = "Joe"
params["student"]["course"]["name"] = "US History"
params["student"]["course"]["topic"] = "History"
Enter fullscreen mode Exit fullscreen mode

Once you can access your information, you can save that information to a variable or instance variable to use in your route or erb file. The values from the params can be used to assign attributes to objects in your database.

Dynamic parameters

Dynamic parameters are used in dynamic routes. A route is simply an HTTP method/verb that is paired within a URL-matching pattern. When you Sinatra application receives a request, it will match that route to a specific controller action that matches the URL pattern. Dynamic parameters are used in routes based on attributes within the URL of the request, these attributes is a variable whose values are set dynamically in a page's URL and can be accessed by its corresponding controller action.

We use dynamic routes because it doesn't make sense to hard-code each route individually ('/medicines/1', '/medicines/2', '/medicines/123') in the controller to display each medicine. This is where dynamic routes come in. In the example below, we want to create a dynamic route that will allow us to get the correct page for the medicine of interest.

# medicines_controller.rb
get '/medicines/:id' do
  @medicine = all_the_medicines.select do |medicine|
    medicine.id == params[:id]
  end.first
  erb :'/medicines/show.html'
end 
Enter fullscreen mode Exit fullscreen mode

The HTTP request verb, GET matches the get method in our controller. The /medicines path in the HTTP request matches the /medicines path in our controller method. The id parameter that's being passed into the path, matches the controller's expectation for an id parameter to be passed in place of :id.

Conclusion

I lost track of the amount of times I went into pry to see the what my params was returning. Params is an important hash to understand when working with Sinatra or Rails. It's a method for users to submit information that is used by the application. Params can also be used for dynamic routes, which allow you to access more routes without having to hard-code each route. When building your Sinatra project, always check your params and understand the format of your params. It'll make your life way easier and save you the headache of grabbing the wrong information from your params.

Top comments (0)