For example, if you have a users table, wait until the user ID array:
Select ID from the users where age > 20;
To implement the above SQL statements, there are several ways to do this in rails:
- User.where (' Age > '). Select (: ID). Collect (&:id)
- User.where (' Age > '). Select (: ID). map (&:id), select ID from ' Users ' where (age < 20)
- User.where (' Age > '). Pluck (: ID), SELECT ' users '. ' ID ' from ' users ' where (age < 20)
The first two methods are the same, which is to isolate the data from the database and then loop through the IDs of the active record's datasets to form an array.
Instead of returning the data set of the active record, the Pluck method simply checks the ID field and returns an array of IDs directly, so we don't need to iterate through the ID array.
Usually, the pluck method is more efficient than the above two methods.
Above rails4.0, pluck can pass multiple fields as parameters.
Person.pluck (: ID,: Name), [[1, ' David '], [2, ' Jeremy '], [3, ' Jose ']
The difference between pluck and select (map, collect) in Ruby on Rails