1
.
12
.
2023
29
.
11
.
2023
Ruby on Rails
Backend
Tutorial

Debugging Rails - Ruby Junior Chronicles

Piotr Witek
Ruby Developer

Debugging is an important skill for software developers. For those working with Ruby on Rails, there are several techniques that can help you spot and fix bugs. In this article, I'll share some practical methods I've used and still use.

1. Displaying Data in Views

As a beginner in Ruby on Rails, I found it useful to display data right in the views. This helped me a lot when dealing with if statements. To understand a problem, I would show the values used in the if statement. This approach made it clear what was happening with the variables, helping me solve the issue.

Example for your index.html.erb file:


<% @users.each do |user| %>
  <p>
    User: <%= user.name %>
    <% if user.age >= 18 %>
      is an Adult
    <% else %>
      isn't an Adult
    <% end %>

    <%# Show user details and the 'if' statement for debugging %>
    Debug Info: <%= user.inspect %>, Adult? = <%= user.age >= 18 %>
  </p>
<% end %>

Here, the debug info shows the user's age and their adult status. This is only for debugging and should be removed for the final version.

2. Using "puts" Statements

puts statements are simple but effective for debugging. They print information to the server console, which is useful for checking what's happening on the server side. For example, to understand a method's behavior, puts can be very enlightening:

In your users_controller.rb:


def show
  # Show params and user details in the console
  puts "Looking at parameters: #{params}"
  @user = User.find(params[:id])
  puts "Checking user: #{@user.inspect}"
end

When you visit a user's page, these statements will show the user's details and parameters in your Rails server console. This confirms you're getting the right user.

Also, always read the messages in the Rails server console. They are detailed and can teach you a lot about what's happening in your application.

3. Using rails console

rails console is a powerful tool for working with your Rails app's models and data via command line. It's perfect for testing code snippets and seeing their effects. You can create a new user, change data, or check database records. Just run rails c or rails console in your terminal, and try commands like user = User.new or User.count.

Bonus tip: You can run the console in sandbox mode, which won't modify your data while you experiment with it. To do this, just run rails console --sandbox.

Read more in Ruby on Rails Guides

4. Debugging with the Pry Gem

Pry gem is a fantastic tool, almost like an enhanced Rails console. You can pause your code with binding.pry in a method in your controller. It's like stopping your code to closely examine variables like user_params. You can even test methods right in the console.


def create
  # Pauses your code for exploration
  binding.pry

  @user = User.new(user_params)

  if @user.save
    redirect_to @user, notice: 'User created.'
  else
    render :new
  end
end

To finish debugging with pry, type quit or exit. It's an excellent way to understand your code deeply.

Read more about https://github.com/pry/pry

Alternative Gems

Apart from pry, gems like byebug and debugger also offer similar debugging features.

5. Using Log Files

Rails automatically creates log files that track activities like requests, database queries, and errors. These logs are crucial, especially in production. You'll find them in the log directory of your Rails app.

  • development.log: Logs for development.
  • production.log: Logs for production.
  • test.log: Logs for testing.

In bigger projects production logs are often sent to 3rd party services like Datadog.

Viewing Log Files

To see a log file, just open it in a text editor or use command-line tools, like tail -f log/development.log.

Example Log Entry


Started GET "/users/1" for 127.0.0.1 at 2023-11-22 12:34:56 +0000
Processing by UsersController#show as HTML
  Parameters: {"id"=>"1"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
  Rendered users/show.html.erb within layouts/application (15.6ms)
Completed 200 OK in 46ms (Views: 30.1ms | ActiveRecord: 0.4ms)

This log entry shows a GET request for /users/1, calling the show action in the UsersController and the database query for the user.

6. Debugging with an IDE - VS Code, RubyMine

IDEs like VS Code or RubyMine have advanced debugging features. They offer a visual interface for setting breakpoints and inspecting variables. Check your IDE's documentation for more on this.

The screenshot shows a RubyMine IDE during a debugging session for an update method in an AddressesController, with a breakpoint set (red dot left to the code) and variables displayed in the debugging panel below the code.

Conclusion

Debugging in Ruby on Rails improves with practice. Start with simple methods like displaying data in views and using puts statements. Use the rails console and pry gem for deeper investigation. Don't forget log files. If you're using an IDE, use its debugging tools. Each debugging challenge is a chance to grow as a Rails developer. Keep experimenting and learning!

Piotr Witek
Ruby Developer

Check my Twitter

Check my Linkedin

Did you like it? 

Sign up To VIsuality newsletter

READ ALSO

WebUSB - Bridge between USB devices and web browsers

14
.
11
.
2023
Burak Aybar
Ruby on Rails
Frontend
Backend
Tutorial

Visuality comes to town - this time it's Poznań

14
.
11
.
2023
Michał Piórkowski
Visuality
HR

CSS Modules in Rails

14
.
11
.
2023
Adam Król
Ruby on Rails
Tutorial
Backend
Frontend

How to choose a software house.

14
.
11
.
2023
Michał Piórkowski
Ruby on Rails
Business
Visuality

JSON API versus the NIH syndrome

14
.
11
.
2023
Nadia Miętkiewicz
Backend
Frontend
Tutorial

From Idea to Concept

02
.
10
.
2024
Michał Krochecki
Ruby on Rails
Business
Startups

Styling React Components

14
.
11
.
2023
Umit Naimian
Ruby on Rails
Frontend
Tutorial

How good design can help your business grow

14
.
11
.
2023
Lukasz Jackiewicz
Design
Business
Marketing

TODO not. Do, or do not.

29
.
11
.
2023
Stanisław Zawadzki
Ruby on Rails
Software

CS Lessons #003: Density map in three ways

14
.
11
.
2023
Michał Młoźniak
Ruby
Backend
Tutorial
Software

Clean code for the win

14
.
11
.
2023
Michał Piórkowski
Ruby on Rails
Backend
Frontend
Business

Crowd-operated Christmas Lights

14
.
11
.
2023
Nadia Miętkiewicz
Ruby on Rails
Backend

How to startup and be mature about it

14
.
11
.
2023
Rafał Maliszewski
Ruby on Rails
Startups
Business

A journey of a thousand miles begins with workshops

14
.
11
.
2023
Michał Piórkowski
Software
HR

CS Lessons #002: Data structures

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

Summary of Phoenix workshop at Visuality

14
.
11
.
2023
Karol Słuszniak
Ruby on Rails
Visuality
Backend

CS Lessons #000: Introduction and motivation

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

CS Lessons #001: Working with binary files

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

Working with 40-minute intervals

14
.
11
.
2023
Sakir Temel
Software
HR

THE MATURE TECH STARTUP DILEMMA: WHAT'S NEXT

14
.
11
.
2023
Susanna Romantsova
Startups

Win MVP workshop!

14
.
11
.
2023
Susanna Romantsova
Startups

FINTECH WEEK IN OSLO: WHATs & WHYs

14
.
11
.
2023
Susanna Romantsova
Conferences

MY FIRST MONTH AT VISUALITY

14
.
11
.
2023
Susanna Romantsova
Visuality
HR

NASA 1st global hackaton in Poland? Visuality Created it!

14
.
11
.
2023
Rafał Maliszewski
Ruby on Rails

Berlin StartupCamp 2016 summary

14
.
11
.
2023
Michał Piórkowski
Conferences
Startups