Chris
Chris

Reputation: 1419

pass object or object id?

Given the following code, which enroll method is better and why? Or should this code be improved some other way altogether?

My idea of "better" for the above basically boils down to 1) most philosophically correct (best practices) and 2) most efficient/performant.

Class Course < ActiveRecord::Base
  has_many :enrollments # basically a join table
  has_many :students, :source => :user, :through => :enrollments
  def enroll_this_way(student)
    self.enrollments << Enrollment.new(:course_id => self.id, :student_id => student.id)
  end
  # OR
  def enroll_that_way(student_id)
    self.enrollments << Enrollment.new(:course_id => self.id, :student_id => student_id)
  end
end

Upvotes: 2

Views: 1481

Answers (2)

Art Shayderov
Art Shayderov

Reputation: 5110

Both are probably not perfect. course#enrollments<<(object, …) sets the foreign keys on enrollment objects, so you don't need to set :course_id on enrollment, alternatively you don't need to call course#enrollments<<(object, …) if foreign key is already set, you just call enrollment#save.

As @zed_0xff pointed to, you can just call course#enrollments#build (or better course#enrollments.create if you want changes to persist to database).

Besides you can safely omit self. There are no ambiguities as to what enrollments and id are.

Highly recommended Rails Guides: 4.3 has_many Association Reference

Edit: I just realized that I didn't answer the OP question. There is no difference at all.

Upvotes: 2

zed_0xff
zed_0xff

Reputation: 33217

def enroll_this_way(student)
  self.enrollments.build :student => student
end

Upvotes: 12

Related Questions