Skip to content

Instantly share code, notes, and snippets.

@scootcho
Last active September 30, 2022 09:23
Show Gist options
  • Save scootcho/8c73f7b7f78fb81c8161 to your computer and use it in GitHub Desktop.
Save scootcho/8c73f7b7f78fb81c8161 to your computer and use it in GitHub Desktop.
rails console commands #rails #console #commands

open gem using bundler (in app root directory)

bundle open gem_name
bundle open activesupport

clear the console

control + l
command + k (mac)

Press <Tab> to reveal all possible actions

Rails.app<tab> show all possible methods

show all tables. Note, the Model is singular of the table name.

ActiveRecord::Base.connection.tables

show which version of gem app is using

bundle show gem_name

open the source code of gem

bundle open gem_name

dump schema from database

rake db:schema:dump

load schema into database

rake db:schema:load

list all rake tasks

rake -T
rake -T assets
rake -T db

if activated gem needs Gemfile requires gem version.

bundle update gem_name

start a console for the database

rails dbconsole

Methods lookup using grep

"".methods.grep(/case/).sort

list instance methods of a class

ClassName.instance_methods

accessing the app object

app
app.host
app.class
app.methods
app.method(:get).source_location
app.main_app
app.main_app.methods
app.root_path
app.root_url
app.user_path(3, sort: "yo yo") #=> "/users/3?sort=yo+yo"
app.name_path
app.project_path(Project.first)
app.get "/users/1"
app.response
app.response.header
app.response.body
app.response.redirect_url
app.session[:user_id]
app.cookies
app.flash

disable CSRF token in console

ApplicationController.allow_forgery_protection = false

app.post "/users/sign_in", email: "foo@bar.com", password: "foobar"

using helpers in the console

helper.methods.sort
helper.title_tag "Testing!"
helper.submit_tag
helper.link_to("Movies", app.movies_path)
helper.instance_variable_set :@project, Project.first
helper.pluralize 2, "story"
helper.javascript_debugging_options
helper.image_tag('test.png')

This pattern (gem-binary gem-version) works for any gem binary.

rails _4.0.0_ new app_name

access the application object (returns MyApp::Application class)

Rails.application

see all configurations

Rails.application.config

reload console

reload!

always run sandbox with production console

rails console production --sandbox

start rails server in different port

rails server -p 3001

locate where methods are defined

location = ModelName.instance_method(:method_name).source_location

launch SublimeText and go directly to the method

subl #{location[0]}:#{location[1]}

all of the below queries are the same

User.where(:email => "foo@bar.com")
User.where("email" => "foo@bar.com")
User.where("email = 'foo@bar.com'")
User.where("email = ?", "foo@bar.com")
User.where("users.email" => "foo@bar.com")

get the Journey::Routes object

Rails.application.routes.routes

List all the URL helpers

Rails.application.routes.named_routes.helpers

recognize_path

Rails.application.routes.recognize_path "/station/index/42.html"
=> {:controller=>"station", :action=>"index", :format=>"html", :id=>"42"}

generate routes

Rails.application.generate(:controller => :station, :action=> :index, :id=>42)
=> /station/index/42

Use jobs to see all the open subsessions

jobs

OpenStruct attributes to be added on the fly

computer = OpenStruct.new(ram: '4 MB', hard_disk: '500 GB')
computer.ram ### => '4 MB'
computer[:hard_disk] ### => "500 GB"
### attributes can be created 'on the fly'
computer.screen = "1024x768"
computer.screen   ### => "1024x768"
computer[:screen] ### => "1024x768"

create object with OpenStruct to pass data to test ActionView

>> helper.controller = OpenStruct.new(params: {})
=> #<OpenStruct params={}>
>> helper.javascript_debugging_options
=> {}
>> helper.controller = OpenStruct.new(params: {javascript_debugging: "enabled"})
=> #<OpenStruct params={:javascript_debugging=>"enabled"}>
>> helper.javascript_debugging_options
=> {:debug=>true, :digest=>false}

use uderscore for value of last evaluated expression

>> 1 + 1
=> 2
>> _
=> 2
>> _ * _
=> 4

use ri to read ruby doc in console

ri File
ri Fil
ri File.directory?
ri Socket#accept
ri ActiveRecord::Base.touch

Getting ri For All of Your Gems (first omit --no-ri from .gemrc)

gem rdoc --all --ri --no-rdocs

raw sql in rails console

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)
#=> returns PostgreSQLG/MySQL result object
records_array.to_a

Roll back all rails migrations or drop tables and modify migrations (start from scratch)

rake db:migrate VERSION=0

Get the current Directory

Dir.pwd

Count files in a directory

Dir["your-directory/**/*"].length


###Resources:

http://pragmaticstudio.com/blog/2014/3/11/console-shortcuts-tips-tricks
https://signalvnoise.com/posts/3176-three-quick-rails-console-tips
http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html
http://api.rubyonrails.org/classes/Rails/ConsoleMethods.html
http://errtheblog.com/posts/24-irb-mix-tape
http://errtheblog.com/posts/41-real-console-helpers
http://www.happybearsoftware.com/assorted-ruby-tips-and-tricks.html
http://www.blackbytes.info/2015/06/using-struct-and-openstruct/
http://ruby-doc.org/stdlib-2.0.0/libdoc/ostruct/rdoc/OpenStruct.html
http://stackoverflow.com/questions/4929078/how-to-sign-in-a-user-using-devise-from-a-rails-console
http://jacopretorius.net/2014/02/all-rails-db-rake-tasks-and-what-they-do.html

Check associations of model

Model.reflections.keys

or

reflections = User.reflect_on_all_associations
reflections.each do |reflection|
  puts ":#{reflection.macro} => :#{reflection.name}"
end
@oraposa
Copy link

oraposa commented Jan 5, 2018

Also

User.where(email: "foo@bar.com")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment