w3d3 rails Flashcards
How do you run migrations
bundle exec rails db:migrate
How do you create a database with rails
set up config/database.yml
bundle exec rails db:create
What are 5 gems to add to rails for development
annotate better_errors binding_of_caller byebug pry-rails
How do you run migrations?
rails db:migrate
Where can you see a copy of your database’s current schema as reported by rails?
db/schema.rb
What’s the best/fastest way to initialize a new database? What does this rely on?
rails db:schema:load
db/schema.rb
How do you enforce that a column must have a value?
within create_table:
t.string :name, null: false
What’s the difference between belongs_to and has_many ?
What do they have in common?
belongs_to exists on the model that contains the primary key
has_many exists on the other model
They allow the use of helper instance methods
What arguments are passed to a belongs_to or has_many association?
(trick) answer: two
better answer: we use ruby’s ability to use a hash as a final argument without braces to pass several options to the association method like so:
belongs_to :table_name, primary_key: :id,
foreign_key: :foreign_key_id,
class_name: ‘SomeClass’
example:
belongs_to :house,
brimary_key: :id,
foreign_key: :house_id,
class_name: ‘House’
What arguments are passed to a belongs_to or has_many association?
(trick) answer: two
better answer: we use ruby’s ability to use a hash as a final argument without braces to pass several options to the association method like so:
belongs_to :table_name, primary_key: :id,
foreign_key: :foreign_key_id,
class_name: ‘SomeClass’
example:
belongs_to :house,
brimary_key: :id,
foreign_key: :house_id,
class_name: ‘House’
What does this do:
validates :attribute, presence: true
It validates that a particular attribute exists on a method when we call #save
How do we validate the uniqueness of an attribute for an object?
Add this to a validates macro:
uniqueness: true
How do we create a custom validator for a model?
- create a method that conditionally shovels an error message into a new key on the self.errors hash
- add this line:
validate :my_validator_method_name
How do we see the errors for an object?
errors.full_messages
What’s the difference between ApplicationModel#save and #save!
save will return false if there are errors.
What’s the difference between ApplicationModel#save and #save!
save will return false if there are errors.
How would you use a symbol as a value in a SQL string?
awesome_symbol: 55
<
What are two levels of data integrity-protection in rails?
DB-level constraints
Model-level validations
Why shouldn’t you roll back a migration?
Can make things out-of-sync with other people working on the same database.
Impossible to keep consistent with a production database.
How do you get to a sql console in rails?
rails db
What is the superclass for all rails models?
ApplicationRecord
What is ApplicationRecord
The superclass that all rails models inherit from.