Thursday, May 24, 2012

:include vs :joins

class User; has_many :leave_credits

then User.where(:id => [1,2]).joins(:leave_credits).count
# => 8 # number of leave_credits.
# SELECT COUNT(*) FROM `users` INNER JOIN `leave_credits` ON `leave_credits`.`user_id` = `users`.`id` WHERE `users`.`id` IN (1, 2)
# may lead to 1+n problem
then User.where(:id => [1,2]).includes(:leave_credits).count
# => 2 # number of users.
# SELECT COUNT(*) FROM `users` WHERE `users`.`id` IN (1,2)
# will not query projects until you call user.leave_credits
# avoids 1+n problem
Other infos: Railscast #181

Thursday, May 17, 2012

Validation

Triggers validation:

  • create
  • create!
  • save
  • save!
  • update
  • update_attributes
  • update_attributes!