parm530
4/4/2018 - 3:48 PM

ActiveRecord

AR in Rails 4

ActiveRecord

  • active record: design pattern for relational databases
  • ActiveRecord: RAILS implementation of the design pattern for relational databases!
  • retrieves objects to manipulate(CRUD) them, not just static rows
user = User.new
user.first_name = ''
user.save #SQL insert

user.delete #SQL delete

ActiveRelation

  • known as Arel
  • Simplifies database queries through the use of chaining methods

Generating a Model

  • from root: rails g modelName (singular name)
    • creates the associated db migration file (table), migrations are PLURAL!!
    • Inherits from ActiveRecord::Base
    • creates file in app/model, model are SINGULAR!!!
  • If you have altered the model name in the database, from users to say admin_users, you can specify in the model that youhave changed model name: self.table_name = 'admin_users'
  • ActiveRecord automatically provides attr_accessors for each field in the model's db! NO NEED TO REWRITE THEM!

Rails console

  • rails c or bundle exec rails c in root of rails app
  • To specify which environment to change into: rails c production, `development is default!

Creating Records

  • new/save:
    • Instantiate
    • Set values
    • 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

Updating a Record

  • find/save method:
    • find the record
    • set values
    • save
  • find/update_attributes method:
    • find the record
    • set values and then save all at once!
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

Deleting a Record

  • find/destroy method
subject = Subject.find(2)
subject.destroy
#returns the object that was destroyed

Using REST to delete

  • As of HMTL5, delete and patch requests are no longer valid to be used in forms!
  • Ensure that you have a destroy action in your model controller that performs the deletion:
def destroy
  @movie.destroy
  redirect_to ..., :notice => "Has been deleted!"
end
  • Next, in your view template:
<%= link_to("Delete", movie_path(movie), method: :delete, :data => {:confirm => "Really?"}) %>
  • When you specify method: :delete and :data => ..., this is using some JavaScript that is built in to rails!
    • The method delete will submit a 'delete' request (will use a 'GET' request if JS is disabled)

Finding Records

#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 table
  • Use the notation below for when you have multiple tables with the same column name:
    • order(table_name.column_name ASC/DESC)
    • Example: order("subjects.created_at ASC")
  • More recent for Rails 5:
    • order(:position)
    • order(position: asc)
    • order("position ASC")
  • limit(integer): reduces the amount of results returned from the query by integer
  • offset(integer): how much results to skip over before returning the results
  • all 3 methods can be chained together!
subjects = Subject.where(visible: true, position: 1)

subjects = Subject.where(["visible = ?", true])