Chapter 5 - Working with Active Record Flashcards
Rails Active Record
The Rails Active Record framework includes mechanisms for representing models and their relationships, CRUD (create, read, update, and delete) operations, complex searches, validation, callbacks, and many more features. It relies heavily on convention over configuration.
In order to create a new model class, the first thing you do is?
In order to create a new model class, the first thing you do is to declare it as a subclass of ActiveRecord:: Base.
class Client
CRUD
Create, Read, Update, and Delete.
new_record?
Returns true if this object hasn’t been saved yet – that is, a record for the object doesn’t exist in the database yet; otherwise, returns false.
persisted?
Returns true if the record is persisted, i.e. it’s not a new record and it was not destroyed, otherwise returns false.
Active Record create
c = Client.create( name: “Nile River, Co.”, code: “NRC”)
Reading Active Record Objects
first_project = Project.find( 1)
all_clients = Client.all
first_client = Client.first
Product.last
String versus Symbol
Many Rails methods accept symbol and string parameters interchangeably, and that is potentially very confusing. Which is more correct? The general rule is to use symbols when the string is a name for something and a string when it’s a value. You should probably be using symbols when it comes to keys of options, hashes, and the like.
Hash Notation
first_client[: name]
Attributes method
first_client.attributes
Being able to grab a hash of all attributes at once is useful when you want to iterate over all of them or pass them in bulk to another function.
attribute_before_type_cast accessors
def fix_rate
self[: rate] =
rate_before_type_cast.tr(‘ $,’,’’)
end
Updating
class ProjectController
Touching Records
> > user = User.first
> > user.touch # = > sets updated_at to now.
> > user.touch(: viewed_at) # sets viewed_at and updated_at to now.
Delete and Destroy
The delete method executes a SQL statement to remove the object’s data from the database . The destroy method will both remove the object from the database and prevent you from
modifying it again:
> > bad_timesheet = Timesheet.find( 1)
> > bad_timesheet.destroy
Timesheet.delete(1)
Locking
Locking is a term for techniques that prevent concurrent users of an application from overwriting each other’s work.