w3d6-w3d7 Flashcards
What is a callback?
Code that is run at a certain moment of an object’s life cycle (i.e. at creation, updating, deletion, etc.)
In an association, what happens to objects that belong to another object when the object they belong to is destroyed (read: the object the foreign key points to is destroyed)?
The objects are considered widowed.
Explain the following code:
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end
When a User is destroyed, the posts that belong to it are destroyed as well.
Where is :dependent added?
In has_many relations.
What are some other options for :dependent?
:nullify
Sets the foreign key to null when its target is destroyed.
How do we guarantee referential integrity?
Add a FOREIGN KEY constraint at the db level.
Explain the following code:
class User true before_validation :ensure_random_code
protected def ensure_random_code # assign a random code self.random_code ||= SecureRandom.hex(8) end end
This is an example of callback registration: the random code attribute is added in case it is forgotten as part of the object’s validation.
What is an important property of callback methods?
They should be protected or private.
What are some useful ActiveRecord callbacks?
before_validation (handy as a last chance to set forgotten fields upon creation, not saving/updating)
• after_create (handy to do some post-create logic, like send a confirmation email)
• after_destroy (handy to perform post-destroy clean-up logic)
Explain the following code:
before_validation(:on => :create) do
self.number = number.gsub(/[^0-9]/, “”) if attribute_present?(“number”)
end
Strip everything but digits, so the user can specify “555 234 34” or
“5552-3434” or both will mean “55523434”
What is wrong with the following ERB:
The Law of Demeter is being violated; objects are talking to objects besides their neighbors/more than one dot is being used.
What does #delegate do and what options does it take?
delegate allows getter methods to be generated for other classes in associations, so that multiple dots are no longer needed. prefix: true can be specified so that sensible prefixes can be given to these getter methods.
Assuming we have an office, doctor, and patient, what code would make the following ERB viable:
class Office < ActiveRecord::Base belongs_to :doctor end
class Doctor < ActiveRecord::Base has_one :office has_many :patients delegate :number, :address, to: :office, prefix: true end
class Patient < ActiveRecord::Base belongs_to :doctor delegate :name, :specialty, :office_number, :office_address, to: :doctor, prefix: true end
T/F: It does not matter what kind of SQL db you’re using; Rails migrations are db agnostic and will work with all of them.
T
What is the first thing that happens when a server running Rails gets a request from a web browser?
It first goes to the Rails router.