It shows a developer in a futuristic software development environment, surrounded by advanced screens displaying various aspects of Ruby on Rails

Exploring Advanced Rails Commands and Methods for Efficient Development

Delve into the specifics of Rails utilities with usage examples.

--

Ruby on Rails, renowned for its efficiency and ease of use, offers several command-line utilities and methods that significantly enhance the development experience. In this article, we explore four such utilities: rails console — sandbox, rails runner, Rails::ConsoleMethods, and .extract_associated, each serving unique and powerful purposes in Rails development.

Rails Console — sandbox

The `rails console — sandbox` command opens the Rails console in sandbox mode. In this mode, any changes you make to the database will be rolled back upon exiting the console. This is incredibly useful for testing and experimenting with data without affecting the actual database state.

Example Usage:

Imagine you want to test a destructive action, like deleting a user:

# Start the Rails console in sandbox mode
rails console --sandbox
# Inside the Rails console
user = User.find(1)
user.destroy
# You can experiment with the user data here
exit
# All changes are rolled back

Rails Runner

rails runner is a command-line utility that runs Ruby code in the context of Rails non-interactively. It’s particularly useful for running scripts that leverage your Rails environment and models.

Example Usage:

Suppose you have a script to update user data:

# In a Ruby script (update_user_data.rb)
User.find_each do |user|
user.update(computed_score: calculate_score(user))
end

# Execute the script with rails runner

rails runner update_user_data.rb

Rails::ConsoleMethods

Rails::ConsoleMethods module is automatically included in the Rails console, providing helpful methods that can be used within the console. These methods enhance the Rails console’s capabilities, making data manipulation and testing more straightforward.

Example Usage:

Using `app` method in Rails console to interact with your application:

--

--

Alessio Bussolari

Ruby on Rails programmer since 2009. Current CTO at COSMIC SRL, where I lead the team in creating innovative solutions.