Learned on the Job Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

What is the difference between find_by! and find_by?

A

The primary difference between find_by and find_by! in Rails lies in their behavior when no record matches the query:

find_by:

Returns nil if no record matches the query.
Does not raise an exception.
Usage: User.find_by(email: params[:email])
find_by!:

Raises an ActiveRecord::RecordNotFound exception if no record matches the query.
Useful when you want to explicitly handle the case where a record is not found, typically with an exception handler.
Usage: User.find_by!(email: params[:email])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

why class_name: ‘Address’ is used:
belongs_to :home_address, class_name: ‘Address’

A

The class_name: ‘Address’ option is specified in the associations to explicitly define the class that the foreign key is associated with. This is necessary because the default association name is derived from the attribute name, which may not always match the actual class name. Let’s break down the reasons for using class_name in this context:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly