Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

ruby - Getting a return without being exact

I have the following code and the return values give me either empty brackets or the name if I give the exact name. How do I get it so that it returns multiple values without having to put in the exact name?

def self.find_all_by_name(name)
  result = self.all.select {|thing| thing.name == name}
  result
end
question from:https://stackoverflow.com/questions/65622987/getting-a-return-without-being-exact

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...