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.

July 15, 2010 - (<= v2.3.8)
2 thanks
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

March 18, 2010 - (v1_8_6_287 - v1_8_7_72)
0 thanks

collect_with_index

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

require 'enumerator'

%w{foo bar}.enum_for(:each_with_index).collect do |item, index| 
  "#{index}: #{item}" 
end

See also: Enumerable#each_with_index