ActiveRecord Flashcards
Starting with a Student
model, how would you join to the schools table and then narrow the results to include only public schools (“category” is “public”)?
Student.join(:schools).where(schools: {category: “public”})
OR
Student.join(:schools).where(“schools.category” => “public”)
How would you retrieve from the data store a group of students who are between the ages of 7 and 9?
Student.where(age: 7..9)
# OR
Student.where(age: [7,8,9])
How do you override accessors for models?
With the read_attribute
and write_attribute
methods.
Due to the nature of the web, the data input by the user will always be strings. ActiveRecord, however, tries to coerce the data into the specified column’s type. How do you access the original data?
model._before_type_cast
How can you store complex data in a single text column?
Model < ActiveRecord::Base
serialize :complex_data
end
How can you force serialized data to be of a specific class?
Pass the class name as the second argument to the serialize
method:
serialize :attribute, OpenStruct
How do you validate that a string matches the pattern /\w+/
?
validates :attributes, format: { with: /\w+/ }
How do you validate that a string is not either “a,” “the,” or “or”?
validates :attribute, exclusion: { in: %w(a the or) }
How do you validate that a shirt size is either “small,” “medium,” or “large?”
validates :size, inclusion: { in: %w(small medium large) }
How do you validate that a password at least 6 characters long?
validates :password, length: { minimun: 6 }
How do you validate that a password is less than 20 characters long?
validates :password, length: { maximum: 20 }
How do you validate that a password is in between 6 and 20 characters?
validates :password, length: { in: 6..20 }
How do you validate that a string is exactly 25 characters long?
validates :attribute, length: { is: 25 }
For length validations, which symbols can you use for error messages?
:wrong_length
:too_long
:too_short
How do you validate that a string has at least 300 words?
validates :attribute, length: {
minimum: 300,
tokenizer: lambda { |str| str.scan(/\w+/) }
}
How do you validate that :age
is a number?
validates :age, numericality: true
How do you confirm that :age
in an integer
validates :age, numericality: { only_integer: true }
What are the acceptable constraints for numericality
?
\:greater_than \:less_than \:greater_than_or_equal_to \:less_than_or_equal_to \:equal_to \:even \:odd
How do you confirm that a string is not nil
or blank?
validates :attribute, presence: true