rails filtering an array after performing a find on the table
i have a method in a model that looks like this:
def self.super_data
self.find(:all,
:select => 'name, type, ref_id, SUM(duration) as duration',
:group => 'name, type, ref_id'
)
end
then I would also like to have a method
def self.filter_by_ref_id(filter_ref_id)
self.select{ |l| l.ref_id == filter_ref_id}
end
so I would like to do model.super_data.filter_by_ref_id(1)
or something like开发者_C百科 that, but it seems like it no longer knows what class it is after the first method, so it can't call the second. is that right? what can I do instead? is this the best way to filter data in rails? thanks!
edit: if you're in rails 3
scope :super_data, select("name, type, ref_id, SUM(duration) as duration").group("name, type, ref_id")
scope :filter_by_ref_id, lambda{ |id| where(:ref_id => id) }
You could define them as scopes:
named_scope :filter_ref_id, lambda { |filter_ref_id| :conditions => {:ref_id => filter_ref_id} }
But I've been using rails 3 for quite some time now, and I don't really remember how chaining scopes works in rails 2...
Have you tried passing in condtions?
def self.super_data(filter_ref_id)
self.find(:all,
:select => 'name, type, ref_id, SUM(duration) as duration',
:group => 'name, type, ref_id',
:conditions => 'ref_id = filter_ref_id'
)
end
精彩评论