If this is just plain Ruby code, which would be odd, then you can simplify it:
def self.find_all_by_name(name)
self.all.select { |thing| thing.name == name }
end
If that doesn't return the correct list of objects then you should verify that your names actually match. One way to test is to dump out the result of:
p self.all.map(&:name)
Check that name matches exactly, as differences in case or additional spaces will cause a string match to fail.
If you want a "contains" type match, you can do:
def self.find_all_by_name(name)
self.all.select { |thing| thing.name.include?(name) }
end
ActiveRecord
If this is ActiveRecord code, or ORM code of some kind, then this ends up loading every record from the database, instantiating models for each one, then comparing the name property. Hugely inefficient and can crash your application, hard if you have a sufficiently large number of records.
What you probably want is to scope things, which is actually way easier:
where(name: name)
Note that the find_all_by_name
method should be auto-generated and do exactly this, anyway, or you can do find_by(name: name)
just the same.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…