DEV Community

jss475
jss475

Posted on

Phase 3 - GET requesting Multiple Pieces of Data

While working on one of my projects recently, I wanted a way to use a GET request to send more than just one piece of data from my database. For example, I have a GET request for a specific product (i.e iPhone) and I wanted to have the information for the product and the seller sent to my frontend.

I had learned in my bootcamp, that you typically just send the information of the product when doing a GET request without any other information. However, while working on the frontend portion of my project, I found it annoying to use .filter methods all the time, or .group and .join methods, to find out who the seller of the product was. It got me thinking because using ruby, you can easily find the seller of a specific product as long as they have a one to many relationship or many to many relationship.

I wanted to leverage that capability and send this information back to my frontend. I had figured out that you can do this by literally just adding a comma between the two pieces of data you want to send back. I'm posting an example of my application controller below to illustrate what I'm talking about

get '/products/:id' do
prod = Product.find(params[:id])
seller_of_prod = prod.seller
combo = prod, seller_of_prod
combo.to_json
end

This piece of code allows you to get information about the product while also getting the seller at the same time. The resulting combo here is a json formatted object with the product and seller. Hope this helps!

Top comments (0)