Params in Sinatra

HarronSam
2 min readMar 16, 2021

It is important to understand how params (parameters) work when building a web app because params are very helpful in the controller files of your app when using the MVC (Model-View-Controller) pattern. Params work like a hash, meaning they contain keys and values that are being passed to the controller through a request (like GET or POST).

A user can pass or set the params hash in the controller from the browser URL in a GET request.

For example, there is the GET method shown below in a controller file

get ‘/cars/:id’ do

@car = Car.find_by(id: params[:id])

erb :cars/show’

end

and if the user types the following into the URL, the application will know where to go.

http://example.com/car/6

Using the GET method and params, the web application would know to find the book that has the specified id in the URL and then set the params hash value to that id. The instance variable, @book, could then be used in your erb :books/show view to display attributes about the book with an id 6.

A POST request can also set a params hash and the params will get passed to the controller from the user submitting of a form.

If there was a view with a form below (The name attribute of an <input> defines how the application will identify each <input> data.)

<form action=”/cars” method=”post”>

<input type=”text” name=”car[make]”>

<input type=”text” name=”car[model]”>

</form>

and the following POST method in a controller.

post ‘/cars’ do

@car = Car.new (params[:car])

end

Once the user submits the form, let’s say with a car make of Ford and the car model of F-150, the controller would pass the hash :car => { :name => “Ford”, :model => “F-150”} to the POST Method. At the post method, @car = Car.new(params[:car]) will become @car = Car.new(make: “Ford”, model: “F-150). Now, after the user submits the form, it is now possible to access that data in the form of a hash where the keys are make and model and the values are Ford and F-150 in this example.

I hope this short blog post will help understanding params a little better.

--

--