Good notes posted by noniq

RSS feed
March 27, 2012
5 thanks

Makes it possible to use a scope through an association

This is a very useful method if you want to to use a scope through an association:

class Book < ActiveRecord::Base
  scope :available, where(:available => true)
end

class Author < ActiveRecord::Base
  has_many :books
  scope :with_available_books, joins(:books).merge(Book.available)
end

# Return all authors with at least one available book:
Author.with_available_books

See http://asciicasts.com/episodes/215-advanced-queries-in-rails-3 for more info.

March 18, 2010
3 thanks

collect_with_index

Use Object#enum_for if you need to collect with index:

require 'enumerator'

['a', 'b', 'c'].enum_for(:each_with_index).collect do |item, index| 
  "#{index}: #{item}" 
end

See also: Enumerable#each_with_index