DEV Community

jgifford82
jgifford82

Posted on • Edited on

Active Record Query Methods

I'm wrapping up the third phase of my coding boot camp. In previous phases, we learned JavaScript and React. The main focus of this phase was learning Ruby. At the end of the phase, we had to complete a web project that ties everything together by building the frontend and creating a backend database. It was interesting to learn how the backend can function to organize data, which creates less work to be done on the frontend. That way, the frontend is mainly concerned with fetch requests rather than having to sort through or manipulate the data after it's fetched. The backend data organization was done using Active Record.

Active Record is a big piece of what we learned in phase 3 in conjunction with Ruby. Active Record is an Object Relational Mapper, or ORM for short. This is the connection between Ruby and our database. It translates the queries we write in Ruby into commands the database understands. It's also a lot easier than writing queries in SQL, since they're written more like plain English.

Active Record queries can be used to retrieve objects from the database, do calculations, retrieve records in a specific order, or limit records retrieved based on certain conditions.

Using an example from my project, I had a section where I wanted to display the ten most recently created events in the database in descending order. Here's how I did that:

    get "/events" do
        events = Event.order(created_at: :desc).limit(10)
        events.to_json
    end

Enter fullscreen mode Exit fullscreen mode

Let's break that down. The .order method retrieves records from the database in a specific order. In the example, Event.order(created_at: :desc) is getting a set of event records and ordering them in descending order by the created_at field in the table. The .limit method is used to specify the number of records to be retrieved. In the example, .limit(10) is retrieving ten records. The .to_json method is used to convert a Ruby hash or array to a valid JSON string. In the example, events.to_json is taking the ten event records and converting them to a JSON string for the frontend side of the application.

This is what the ten most recently created events looks like on my website:

Image description

When I first started my project, I realized I could just chain all the methods together, rather than using a variable and breaking out methods on separate lines like I did in the example above. I thought it made more sense since it was less code to write out and easier to read. I learned the hard way that while it may work, it may not always be a best practice. It may be ok with smaller, simpler code blocks like the one below. I set it up for deleting a specific event in my table by chaining together the find, destroy, and to_json methods.

    delete "/events/:id" do
        Event.find(params[:id]).destroy.to_json
    end

Enter fullscreen mode Exit fullscreen mode

However, chaining everything together for a patch request wasn't ideal. This is what I did at first:

    patch "/events/:id" do 
        Event.find(params[:id]).update(
            venue: params[:venue],
            date: params[:date],
            time: params[:time]
        ).to_json
    end

Enter fullscreen mode Exit fullscreen mode

While this was working on the backend to update an event in my table, it was giving me trouble on the frontend. The frontend patch request was console logging "true" when I was expecting it to return the updated event object. This article helped me realize that to_json returns "true" by default. Breaking out each method separately using a variable as shown below solved the problem. It's cleaner to do it this way for longer, more complex code blocks.

    patch "/events/:id" do 
        event=Event.find(params[:id])
        event.update(
            venue: params[:venue],
            date: params[:date],
            time: params[:time]
        )
        event.to_json
    end
Enter fullscreen mode Exit fullscreen mode

Overall, I really enjoyed learning Ruby and Active Record! It felt more straightforward than JavaScript or React, and it's fun using the methods for organizing data.

Resources:
https://guides.rubyonrails.org/active_record_basics.html
https://guides.rubyonrails.org/active_record_querying.html

Top comments (0)