开发者

Is there easy way to search in fetched records?

So, I want to search in fetched records:

p = Product.added_today # Get records by scope

# wants something 开发者_StackOverflow中文版like
p.search(:name => 'Clocks')

Is there easy (rails way) to do it (gem or something)?


Try this:

pa =  Product.added_today
pa.select{|p| p.name == "Clocks"}


You can use the following Rails features to mimic that kind of search.

  • In Rails 2 you can use Named Scopes
  • In Rails 3 you can use Arel (See the Readme section)


Try building on your scope:
Product.added_today.find(:all, :conditions => {:name => 'Clock'})


one way would be using ruby's find_all -

q = p.find_all{ |e| e.name == 'Clocks' }

as this this code uses brute force ruby array search, performance isn't great. if you expect p to contain more than a few tens of elements, using database queries would be better, performance wise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜