Sinatra & Params

Sam Troutman
2 min readMar 20, 2021

An explainer for params as part of my Flatiron School Sinatra assessment.

Params, short for parameters, are hash of key-value pairs encoded in a HTTP requests. The params are passed to the controller through the HTTP GET or POST request, and can be called to access form data where the key is the name of the data, and the value is the data itself.

In my Sinatra app, I created a bookshelf where users can create a username and password which is then accessed for signup and login with params. This is shown in my UsersController class method:

post '/signup' doif params[:username] == "" || params[:password] == ""redirect to '/signup'else@user = User.new(:username => params[:username], :password => params[:password])@user.savesession[:user_id] = @user.idredirect to "/books"endend

Additionally, users can input book information and their ratings through an HTML form, using a POST request. After the user fills out the form and submits the information, the information fills the params hash. The form information can be accessed, saved to a variable, and used to assign attributes to objects.

Params also came in handy when creating dynamic routes to access individual books. Rather than having to code each route to a book a user creates myself (‘/books/1’ or ‘/books/50’) params allowed me to create a more generic ‘/books/:id’ where the GET request matches the parameter with its id key.

get '/books/:id' do@book = Book.find_by_id(params[:id])if @bookif logged_in? && @book.user_id == current_user.iderb :'/books/show'elseredirect to '/books'endelseredirect to '/books'endend

To sum up: the params hash is data that we get from forms that we are able to use in our controllers. Params are accessible throughout our Sinatra controllers, and can be used to access and manipulate, as well as create dynamic routes.

--

--