The difference between pluck and select (map, collect) in Ruby on Rails

Source: Internet
Author: User
Tags ruby on rails

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:

    1. User.where (' Age > '). Select (: ID). Collect (&:id)
    2. User.where (' Age > '). Select (: ID). map (&:id), select ID from ' Users ' where (age < 20)
    3. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.