Jackson Henley
Jackson Henley

Reputation: 1531

Possible to use ActiveRecord methods on objects loaded from db?

I would like to apply the "find_all_by..." method to records that have already been retrieved by User.all. Is this possible? At this point I am getting an "undefined method `find_all_by_type" error:

rows = User.all
rows.each do |r|
  result = rows.find_all_by_type(r.type)
end

Upvotes: 0

Views: 45

Answers (1)

Jim Stewart
Jim Stewart

Reputation: 17323

Once the records are loaded, you can use any Enumerable method on the collection. What you're looking for here is select:

rows = User.all
rows.each do |r|
  result = rows.select {|row| row.type == r.type}
end

Although I do wonder what you're actually trying to do here. If this is pseudocode or a simplified example, then you can probably apply my code above. You may be better off with this though:

rows = User.all.group_by(&:type)

Upvotes: 1

Related Questions