开发者

After find() does ActiveRecord support accessing/seeking in memory row by particular field value (BESIDES seeking using primary key)?

In the .Net universe I can use 开发者_运维百科an arbitrary SELECT statement and load many rows into DataTable object. I can then find various DataRows using various field criteria (Name='Jack', Age=34, etc.).

In Ruby on Rails, after doing this to load all employees into memory

rs = Employee.find(:all)

I want to seek a row based an arbitrary criteria.

row = rs.seek(:name => 'Jack')

Does ActiveRow support this? I can't seem to find anything or I'm not using the correct terminology.

If not I'll have to walk all rows and build my own hash tables.


Assuming you have a really good reason for fetching all the data and then filtering it, as opposed to using Rails dynamic finders or scopes.

ActiveRecord find returns an Array as others have commented above. You were really close, but the Array method you need is find (defined in module Enumerable)

all_employees = Employee.find(:all)

jack = all_employees.find { |employee| employee.name == 'Jack' }


Employee.find(:all)

will return an array of ActiveRecord instances, so you can either search the array for the relevant records or do something like this:

row = Employee.find_by_name('Jack')

or

rows = Employee.find_all_by_name('Jack')

in order to select the rows you are interested in.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜