简体   繁体   中英

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.

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.

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' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM