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

LLM Embeddings in Ruby - Paweł Strzałkowski

LLM Embeddings in Ruby

17
.
03
.
2024
Paweł Strzałkowski
Ruby
LLM
Embeddings
ChatGPT
Ollama
Handling Errors in Concurrent Ruby, Michał Łęcicki

Handling Errors in Concurrent Ruby

14
.
11
.
2023
Michał Łęcicki
Ruby
Ruby on Rails
Tutorial
Recap of Friendly.rb 2024 conference

Insights and Inspiration from Friendly.rb: A Ruby Conference Recap

02
.
10
.
2024
Kaja Witek
Conferences
Ruby on Rails

Covering indexes - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Ruby on Rails
Postgresql
Backend
Ula Sołogub - SQL Injection in Ruby on Rails

The Deadly Sins in RoR security - SQL Injection

14
.
11
.
2023
Urszula Sołogub
Backend
Ruby on Rails
Software
Michal - Highlights from Ruby Unconf 2024

Highlights from Ruby Unconf 2024

14
.
11
.
2023
Michał Łęcicki
Conferences
Visuality
Cezary Kłos - Optimizing Cloud Infrastructure by $40 000 Annually

Optimizing Cloud Infrastructure by $40 000 Annually

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

Smooth Concurrent Updates with Hotwire Stimulus

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

Freelancers vs Software house

02
.
10
.
2024
Michał Krochecki
Visuality
Business

Table partitioning in Rails, part 2 - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Backend
Postgresql
Ruby on Rails

N+1 in Ruby on Rails

14
.
11
.
2023
Katarzyna Melon-Markowska
Ruby on Rails
Ruby
Backend

Turbo Streams and current user

29
.
11
.
2023
Mateusz Bilski
Hotwire
Ruby on Rails
Backend
Frontend

Showing progress of background jobs with Turbo

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

Table partitioning in Rails, part 1 - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Backend
Ruby on Rails

Table partitioning types - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Backend

Indexing partitioned table - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Backend
Postgresql
SQL Views in Ruby on Rails

SQL views in Ruby on Rails

14
.
11
.
2023
Jan Grela
Backend
Ruby
Ruby on Rails
Postgresql
Design your bathroom in React

Design your bathroom in React

14
.
11
.
2023
Bartosz Bazański
Frontend
React
Lazy Attributes in Ruby - Krzysztof Wawer

Lazy attributes in Ruby

14
.
11
.
2023
Krzysztof Wawer
Ruby
Software

Exporting CSV files using COPY - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Postgresql
Ruby
Ruby on Rails
Michał Łęcicki - From Celluloid to Concurrent Ruby

From Celluloid to Concurrent Ruby: Practical Examples Of Multithreading Calls

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

Super Slide Me - Game Written in React

14
.
11
.
2023
Antoni Smoliński
Frontend
React
Jarek Kowalewski - ILIKE vs LIKE/LOWER - Postgres Stories

ILIKE vs LIKE/LOWER - Postgres Stories

14
.
11
.
2023
Jarosław Kowalewski
Ruby
Ruby on Rails
Postgresql