Table of Content
Rails console
Rails console is a quick way to test the model before writing the controller and views. It let you quering your data storage and playing with the active_record commands.
quering your data storage and playing with the active_record commands
Open your terminal, goes into the rails project folder and run the following command.
$ rails console
This would launch the rails environment and loads the irb.
Note: irb
is the interactive ruby console to let you quickly test some ruby expressions.
In the following, we query the model Comment.
irb(main):002:0> Comment
=> Comment(id: integer, name: string, content: text, created_at: datetime, updated_at: datetime, job_id: integer)
Now we can create new comment object right directly in console.
irb(main):003:0> c = Comment.new
=> #<Comment id: nil, name: nil, content: nil, created_at: nil, updated_at: nil, job_id: nil>
irb(main):004:0> c.name = "Thomas"
=> "Thomas"
irb(main):005:0> c.content = "test"
=> "test"
Note: if you want to run the rails console
in different environment, you can run with RAILS_ENV
.
RAILS_ENV=production rails console
Associating job to comment.
irb(main):006:0> c.job = Job.first
Job Load (0.2ms) SELECT "jobs".* FROM "jobs" LIMIT 1
=> #<Job id: 1, title: "111111", content: "11111", created_at: "2013-09-13 07:03:30", updated_at: "2013-09-13 07:27:17", category: "ruby", salary: 10000, valid_till: "2023-09-13">
irb(main):007:0> c
=> #<Comment id: nil, name: "Thomas", content: "test", created_at: nil, updated_at: nil, job_id: 1>
Now let’s save it.
irb(main):008:0> c.save
(0.1ms) begin transaction SQL (12.0ms) INSERT INTO "comments"("content", "created_at", "job_id", "name", "updated_at") VALUES (?, ?, ?, ?, ?) [["content", "test"], ["created_at", Wed, 18 Sep 2013 15:36:11 UTC +00:00], ["job_id", 1], ["name", "Thomas"], ["updated_at", Wed, 18 Sep 2013 15:36:11 UTC +00:00]]
(0.9ms) commit transaction
=> true
irb(main):009:0> c
=> #<Comment id: 1, name: "Thomas", content: "test", created_at: "2013-09-18 15:36:11", updated_at: "2013-09-18 15:36:11", job_id: 1>
Selecting all comments for a job object and its associated comments.
irb(main):010:0> j = Job.first
Job Load (0.4ms) SELECT "jobs".* FROM "jobs" LIMIT 1
=> #<Job id: 1, title: "111111", content: "11111", created_at: "2013-09-13 07:03:30", updated_at: "2013-09-13 07:27:17", category: "ruby", salary: 10000, valid_till: "2023-09-13">
irb(main):011:0> j.comments
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."job_id" = 1
=> [#<Comment id: 1, name: "Thomas", content: "test", created_at: "2013-09-18 15:36:11", updated_at: "2013-09-18 15:36:11", job_id: 1>]
And we can also count it.
irb(main):018:0> j.comments.count
(0.3ms) SELECT COUNT(*) FROM "comments" WHERE "comments"."job_id" = 1
=> 1
What’s next? We’re going to take a look at “Lab – Adding category”.