Rails: Passing Parameters to your page; Using user input

If you’re like me, you comprehend the gets.chomp methods as a way to gather information from your user. Rather fortunately however, the command line isn’t really available to your user and they probably wouldn’t know what to do with it if it were. We are accustomed to clicking links and the application rendering a new view with your item featured. Etsy would be quite clunky if you could never view an item you like by itself. Sorting how rails accomplishes this is a trickier topic than most tutorial basics show you, but at the same time, the only other advanced tutorials tend to be overly wordy and convoluted.

Lets pick apart a popular way of getting user defined parameters and using them accordingly. Lets say we have a run-of-the-mill eCommerce rails app.

# we have a landing route to the list of all products
# when a user inputs <domain>/home into their browser...

# config/routes.rb
get '/home' => 'products#show_all

# when the browser goes to the /home url,
 the products controller starts the show_all method.

# this gets triggered in /app/controllers/products_controller.rb
class ProductsController < ......

    def show_all
         @products = Product.all
    end

end

At this point, @products is a variable made available to us on the show_all.html.erb view. It contains all the objects of class Product and can be iterated and manipulated accordingly. But what if you want to see a particular item, say, the Product with ID #2 in the database?

# to see this Product with ID#2 the user needs to pass
 Parameters along with the get request

# this time the user is going to type into their browsers
 address bar: "<domain>/products/2"

#config/routes.rb showing previous path and NEW PATH needed:
get '/home' => 'products#show_all
get '/products/:item_number' => 'products#show_product'

# now we need a new method to make use of the route defined above
class ProductsController < ......
    def show_all
        @products = Product.all
    end

    # this is when we use params to pass the variable
 in the route (:id) to the controller 

    def show_product
       @product = Product.find_by(id: params[:item_number]) 
    end
end

Now @product is available to your view. It will be unique because you used it’s database id to look it up. This can be trickier when searching by name or other non unique attributes, but with the default :id it’s a sure fire thing. Hopefully this is just simple and basic enough to help you wrap your head around the concept and get it working. Don’t worry about feature functionality at this point. It’s important to know these mid level skill things and how they work, even if a user would never operate your app this way.

Rails: Passing Parameters to your page; Using user input