w3d3_notes Flashcards
What does Singleton enforce? Why does this matter for databases?
Singleton enforces a single instance of a class (interact with it via ‘instance’). For a class with a db connection, this means that only one connection to the database is maintained.
How can an SQL injection be achieved?
By inserting a string with semicolons:
“blahblahblah; DROP TABLE;”
If the characters (namely the semicolons) are not escaped, then the malicious code will be executed.
When should you NOT use the hash declaration shortcut syntax:
{id: ‘id’, val: 0}
When you do NOT want your keys to be symbols.
T/F: An attr_accessor is fine for all column values.
F; :id should be an attr_reader b/c you want it to be immutable. Not that Rails does NOT do this.
Are N+1 queries good?
NO, THEY ARE EVIL! Multiple database queries are expensive (imagine trying to repeatedly query a server halfway across the world: the lag will be VERY noticeable!)
If SQL can take care of it, have SQL do it!
What is the SQL algorithm to retrieve all users form a db?
SELECT
COUNT(*)
FROM
users
Why should you start with the where clause?
If you do not specify what you want, you run the risk of accessing all records in the db (the default). This means that, for example, an update statement for one user’s password where you forget the WHERE clause will change everyone’s password!
What is the command to generate a migration?
$rails generate migration migration_name
What is the difference between ::create and ::create!
Both versions create a new instance of the class and insert it into the db. Both return true when they succeed, however on failure the bang version will raise an exception whereas the safe version will return false (a “quiet failure”
What is the command to reload the rails console?
reload!
What must migrations include in the create table iterations?
t.timestamps
What is a good way to think about foreign keys?
A king has many subjects, subjects belong to the king.
In this example, the king has the primary key :id, whereas the subjects have the foreign key :king_id
What should you do when you have a bad db connection in rails?
Check database.yml to make sure that the username (for the dev environment) is the name of the local user.
What is the difference between ::find_by and ::where in ActiveRecord?
find_by will return a single instance, whereas where will return an array of instances, even if there is only one match.
T/F: You should always declare associations in both directions.
T