AR in Rails 4
active record
: design pattern for relational databasesActiveRecord
: RAILS implementation of the design pattern for relational databases!user = User.new
user.first_name = ''
user.save #SQL insert
user.delete #SQL delete
Arel
rails g modelName
(singular name)
ActiveRecord::Base
app/model
, model are SINGULAR!!!users
to say admin_users
,
you can specify in the model that youhave changed model name: self.table_name = 'admin_users'
attr_accessor
s for each field in the model's db! NO
NEED TO REWRITE THEM!rails c
or bundle exec rails c
in root of rails apprails c production
, `development is default!new
/save
:
subject = Subject.new
subject.new_record? #is it a new object? (not in db)
subject.name = "Example 1"
#for faster attribute assignment: MASS ASSIGNMENT
subject = Subject.new(name: "Example1", position: 1, visibible: true)
#finally, save the record to the database:
subject.save
#Outputs the SQL used to save the record, RETURNS either true(saved) or false(not saved)
#Adds the id field
subject.new_record? #false, its in the db already
create
:subject = Subject.create(name: "Example1", position: 1, visibible: true)
#RETURNS the object the was saved to the DB
find
/save
method:
find
/update_attributes
method:
subject = Subject.find(1) #find with id=1
subject.name = "Initial example" #set value
subject.save #SQL that is run using update method
#Using mass assignment:
subject = Subject.find(2)
subject.update_attributes(name: "Blah", position: 2, visible: true)
#runs another update SQL and returns true or false
find
/destroy
methodsubject = Subject.find(2)
subject.destroy
#returns the object that was destroyed
delete
and patch
requests are no longer valid to be used in forms!destroy
action in your model controller that performs the deletion:def destroy
@movie.destroy
redirect_to ..., :notice => "Has been deleted!"
end
<%= link_to("Delete", movie_path(movie), method: :delete, :data => {:confirm => "Really?"}) %>
method: :delete
and :data => ...
, this is using some JavaScript that is
built in to rails!
#primary key finder, returns object or error
subject.find(3) #finds subject with id of 3
#dynamic finder
subject.find_by_id(1) #returns nil if not found or the object if found
subject.find_by_any_valid_database_column_name()
#class method that finds all records
Subject.all #returns array with the collection of subjects
Subject.first #returns first item
Subject.last #returns last item
order(arg)
: can be ordered by any column in the database tableorder(table_name.column_name ASC/DESC)
order("subjects.created_at ASC")
order(:position)
order(position: asc)
order("position ASC")
limit(integer)
: reduces the amount of results returned from the query by integeroffset(integer)
: how much results to skip over before returning the resultssubjects = Subject.where(visible: true, position: 1)
subjects = Subject.where(["visible = ?", true])