2

I am using Ruby on Rails 3.2.2 and I would like to know if it is possible to run a method on each record retrieved when "running" / "loading" an ActiveRecord::Relation so to "keep" / "return" only those records for which that method returns true until those are 5. That is, I have:

class Comment < ActiveRecord::Base
  def method_name
    # return 'true' or 'false'
  end
end

# The '<...>' in the below code could / should be stated to run the 'method_name'
# on each comment and keep those comments for which 'method_name' returns 'true' 
# until the count of retrieved comments is 5.
Comment.where(:published => true).<...> 
Comment.<...> 
user12882
  • 4,702
  • 9
  • 39
  • 54
  • That would imply loading one object per query which is awfully inefficient. – Sergio Tulentsev Jun 17 '12 at 21:59
  • Why not use a scope and lambda? Have a look here: http://stackoverflow.com/questions/1476678/rails-named-scope-lambda-and-blocks and at the guides: http://guides.rubyonrails.org/active_record_querying.html#scopes – Jasper Kennis Jun 17 '12 at 22:00
  • @Sergio Tulentsev - I know, but it is just until the count of retrieved comments is 5. – user12882 Jun 17 '12 at 22:00
  • @Jasper Kennis - The problem is how to properly use `lambda` to accomplish what I would like to make? – user12882 Jun 17 '12 at 22:02
  • Here's an approach, haven't tested this though, might return all results first and then apply the second method. http://www.dzone.com/snippets/how-use-limit-rails-namedscope – Jasper Kennis Jun 17 '12 at 22:50
  • 1
    Or, probably better, try the limit method: http://m.onkey.org/active-record-query-interface – Jasper Kennis Jun 17 '12 at 22:52
  • do you want to call method_name to the first 5 published commments? in this case simply use limit. Or you want to use it as a filter? in that case you better keep it in a db column and use scope like with published. – Viktor Trón Jun 18 '12 at 00:48
  • @user12882 Did this get resolve? – red-devil Sep 03 '19 at 16:02

0 Answers0