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

A look back at Friendly.rb 2023

14
.
11
.
2023
Cezary Kłos
Conferences
Ruby

Debugging Rails - Ruby Junior Chronicles

14
.
11
.
2023
Piotr Witek
Ruby on Rails
Backend
Tutorial

GraphQL in Ruby on Rails: How to Extend Connections

14
.
11
.
2023
Cezary Kłos
Ruby on Rails
GraphQL
Backend
Tutorial

Tetris on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Backend
Frontend
Hotwire

EURUKO 2023 - here's what you've missed

14
.
11
.
2023
Michał Łęcicki
Ruby
Conferences

Easy introduction to Connection Pool in ruby

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Backend
Ruby
Tutorial

When crazy ideas bring great time or how we organized our first Conference!

04
.
12
.
2023
Alexander Repnikov
Ruby on Rails
Conferences
Visuality

Stacey Matrix & Takeaways - why does your IT project suck?

02
.
10
.
2024
Wiktor De Witte
Project Management
Business

A simple guide to pessimistic locking in Rails

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Backend
Ruby
Tutorial

Poltrax design - story of POLTRAX (part 3)

04
.
12
.
2023
Mateusz Wodyk
Startups
Business
Design

Writing Chrome Extensions Is (probably) Easier Than You Think

14
.
11
.
2023
Antoni Smoliński
Tutorial
Frontend
Backend

Bounded Context - DDD in Ruby on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Domain-Driven Design
Backend
Tutorial

The origin of Poltrax development - story of POLTRAX (part 2)

29
.
11
.
2023
Stanisław Zawadzki
Ruby on Rails
Startups
Business
Backend

Ruby Meetups in 2022 - Summary

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Visuality
Conferences

Repository - DDD in Ruby on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Domain-Driven Design
Backend
Tutorial

Example Application - DDD in Ruby on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Domain-Driven Design
Backend
Tutorial

How to launch a successful startup - story of POLTRAX (part 1)

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

How to use different git emails for different projects

14
.
11
.
2023
Michał Łęcicki
Backend
Tutorial

Aggregate - DDD in Ruby on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Domain-Driven Design
Backend
Tutorial

Visuality at wroc_love.rb 2022: It's back and it's good!

14
.
11
.
2023
Patryk Ptasiński
Ruby on Rails
Conferences
Ruby

Our journey to Event Storming

14
.
11
.
2023
Michał Łęcicki
Visuality
Event Storming

Should I use Active Record Callbacks?

14
.
11
.
2023
Mateusz Woźniczka
Ruby on Rails
Backend
Tutorial

How to rescue a transaction to roll back changes?

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Backend
Ruby
Tutorial