Why associations in rails…?

Why associations…?

In Rails, an association is a connection between two Active Record models. Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for colleges and a model for students. Each college has many students. Without associations, the model declarations would look like this:

class College < ApplicationRecord
end

class Student < ApplicationRecord
end

Adding a student to a particular college

@student = Student.create(name: "Tim John", cgpa: "9.0", 
college_id: @college.id) #=> Student id: 1, college_id: 1, name: "Tim John",
created_at: 2017-09-23 22:28:19 +0530, updated_at: 2017-09-23 22:28:19 +0530

Removing a student to a particular college

@students = Student.where(college_id: @college.id)
@students.each do |student|
  student.destroy
end

@college.destroy

The code becomes repetitive for adding or removing the student from the college. It code doesn't really become DRY. Instead using associations, we have a meaningful way of adding and removing objects without ambiguity as well as DRY code.

With Active Record associations,

class College < ApplicationRecord
  has_many :students, dependent: :destroy
end

class Student < ApplicationRecord
  belongs_to :college
end

@student = @college.students.create(name: "Tim John", cgpa: "9.0")
#=> Student id: 1, college_id: 1, name: "Tim John", 
created_at: 2017-09-23 22:28:19 +0530, updated_at: 2017-09-23 22:28:19 +0530

Note the difference between build and create

@student = @college.students.build(name: "Tim John", cgpa: "9.0")
#=> Student id: nil, college_id: 1, name: "Tim John", 
created_at: nil, updated_at: nil

creates a object with reference, but doesn't save it into db.

@student = @college.students.create(name: "Tim John", cgpa: "9.0")
#=> Student id: 1, college_id: 1, name: "Tim John", 
created_at: 2017-09-23 22:28:19 +0530, updated_at: 2017-09-23 22:28:19 +0530

creates a object with reference, and saves it into the db.

Note :

build and create have different methods for different associations. Say, @college.students.build for has_many and @college.build_student for has_one association.

Note the difference between save, save! and create, create!

save! and create! performs all validations and callbacks. If any validation returns false, save! and create! throws an error and cancels the object saving it to db.

save and create does not throw any error in the case above, but cancels the object saving into the db. Also, the methods for validations can be bypassed.

The Types of Associations

Rails supports six types of associations:

belongs_to
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many

Will look into all associations in next upcoming posts. See ya 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *