Here are two sample codes.
First one with collect:
User.first.gifts.collect(&:id)
Second one with pluck:
User.first.gifts.pluck(:id)
Is there any difference between them in performance or something else?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
pluckis on the db level. It will only query the particular field. See this.When you do:
You have objects with all fields loaded and you simply get the
idthanks to the method based on Enumerable.So:
if you only need the
idwith Rails 4, useids:User.first.gifts.idsif you only need some fields with Rails 4, use
pluck:User.first.gifts.pluck(:id, :name, ...)if you only need one field with Rails 3, use
pluck:User.first.gifts.pluck(:id)if you need all fields, use
collectif you need some fields with Rails 4, still use
pluckif you need some fields with Rails 3, use
selectandcollect