ruby on rails - Methods for ActiveRecord that not implies database or convert into Hash/Array -
i have model foo , in index action do:
@foos = foo.all and now, on view want know if @foos contain record whit foo.id = whatever
one method of @foos.exists?(id: whatever), method implies bd query , want avoid this.
other method @foos.collect(&:id).include?(whatever) implies conversion of @foos array, case avoid.
there ways accomplish it?
thanks in advance
update
i want object not know if exists, sorry bad explanation.
you can use enumerable#any? check if value exists in array of results:
@foos.any? { |foo| foo.id == whatever } this check performed on result array without hitting database again , without converting array structure.
update
if want object returned, use enumerable#find, this:
@foos.find { |foo| foo.id == whatever } this return first occurrence foo.id == whatever.
Comments
Post a Comment