Rails and psql console basics - Evanto/qna GitHub Wiki

rails console (rails c)

1. List table column names

ActiveRecord: List columns in table from console:
Model.column_names
=> ["id", "user_id", "body", "commentable_type", "commentable_id", "created_at", "updated_at"]

2. Create an objects with all params

comment = Comment.create(id: 3, user_id: 3, body: "wg3", commntable_type: "Question", commentable_id: 25)

3. Check the number of records in a table

Model.count
=> 3

4. Delete all records from a table

Model.destroy_all
if after this you check the number of records in this table with Model.count, the result will be 0.

psql console

1. Switch to your db console

rails db
this will bring you to the console of your project db (if you work in PG, it will be a pg console, if SQlite - sqlite console, etc.

2. View a pesific table from psql db console (psql command line interface)

TABLE mytablename; (for newer versions)
example:
TABLE comments;
to go back (exit viewing the table), press q
Longer, but works for all versions:
SELECT * FROM comments;
To see only 10 records of a table:
SELECT * FROM comments LIMIT 10;
If a table is too wide (big rows), switch to another table view with \x (toggle expanded display on). It shows the rows in key/value pairs for each object (instead of tabulated):
\x
SELECT * FROM comments LIMIT 10;
how do I exit the /x table mode?

3. Insert new rows into a tabe (crea a new item)

INSERT

4. List all commands

\? Various useful psql commands get the name of a Ruby class

5. Exit psql console

\q