Active Record Flashcards
What is active record?
Active record is the model in the MVC framework. It is where the data and business logic are specified. In Active Record objects have both persistent data and methods to operate on that data.
What is ORM?
Object Relational Mapping: a system for connecting objects to tables in a relational database, without having to directly write SQL statements.
What would the table name be for the model Post?
posts
What would the table name be for the class LineItem?
line_items
What would the schema name be for the class Person?
people
What are the optional column names?
created_at updated_at lock_version type (association_name)_type (table_name)_count
How can you create an Active Record without using the rails generator?
Create a subclass of the ActiveRecord::Base class. Normally this would be in a ModelName.rb file, in the Models directory. class ModelName < ActiveRecord::Base end
How do you get a model to check if a variable has been set before saving?
validates :variable_name, presence: true
How do you set a many to one relationship between two models?
On the first line of the the model.rb file for ModelA write
has_many :model_bs
On the first line of the the model.rb file for ModelB write
belongs_to :model_as
Note that you are using :symbols to name the models
In a model.rb file, how can you set a variable’s default value?
Add the line of code to the top of the file:
before_create :method_name
where the method_name is a private method defined in the model.rb file.
How can you update variables automatically calculated in a model file?
Add the line of code to the top of the model.rb file:
before_save :method name
where the method_name is a private method defined in the model.rb file.
How can you define methods that are private to the controller or model class?
in the model.rb or controller.rb file add a line
private
All methods defined below will this line will be private to the class.
What is the difference between validate and validates in a rails model.rb file?
validate gives you access to all the rails default validate methods.
validates adds a custom validation method to the class
How do you add a validation to a rails model to ensure that a value is a positive integer?
validates :num_var, presence: true, numericality: { only_integer: true, greater_than: 0 }
How do you create a custom validation?
In the model.rb file put:
validate :thing_present
private def thing_present id thing.nil? errors.add(:thing, "is not a valid thing or is not present") end end