Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 822
Chris Avatar asked Jun 30 '26 03:06

Chris


2 Answers

def enroll_this_way(student)
  self.enrollments.build :student => student
end
like image 98
zed_0xff Avatar answered Jul 01 '26 21:07

zed_0xff


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.

like image 25
Art Shayderov Avatar answered Jul 01 '26 23:07

Art Shayderov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!