Skip to content
This repository

Add Model.pluck method like ActiveRecord #2337

Closed
wants to merge 1 commit into from

3 participants

Jason Lee Don't Add Me To Your Organization a.k.a The Travis Bot Durran Jordan
This page is out of date. Refresh to see the latest.

Showing 2 changed files with 37 additions and 0 deletions. Show diff stats Hide diff stats

  1. +12 0 lib/mongoid/finders.rb
  2. +25 0 spec/mongoid/finders_spec.rb
12 lib/mongoid/finders.rb
@@ -129,6 +129,17 @@ def first
129 129 def last
130 130 with_default_scope.last
131 131 end
  132 +
  133 + # Pick up values array by a column
  134 + #
  135 + # @example Pick up all email from User model
  136 + # User.pluck(:email)
  137 + #
  138 + # @return [ Array ] The all values in column
  139 + def pluck(column_name)
  140 + column_name = column_name.to_sym
  141 + with_default_scope.all.only([column_name]).map(&column_name)
  142 + end
132 143
133 144 protected
134 145
@@ -144,5 +155,6 @@ def last
144 155 def find_or(method, attrs = {}, &block)
145 156 where(attrs).first || send(method, attrs, &block)
146 157 end
  158 +
147 159 end
148 160 end
25 spec/mongoid/finders_spec.rb
@@ -428,6 +428,31 @@
428 428 end
429 429 end
430 430 end
  431 +
  432 +
  433 + describe "#pluck" do
  434 + it "work" do
  435 + Person.create(title: "Senorita")
  436 + Person.create(title: "Jason")
  437 + Person.pluck(:title).should eq(%w(Senorita Jason))
  438 + end
  439 +
  440 + context "work with Criteria" do
  441 + before do
  442 + Person.create(title: "Senorita")
  443 + Person.create(title: "Jason", pets: true)
  444 + Person.create(title: "Tim")
  445 + end
  446 +
  447 + it "with where" do
  448 + Person.where(pets: false).pluck(:title).should eq(%w(Senorita Tim))
  449 + end
  450 +
  451 + it "with limit" do
  452 + Person.where(pets: false).limit(1).pluck(:title).should eq(%w(Senorita))
  453 + end
  454 + end
  455 + end
431 456
432 457 Origin::Selectable.forwardables.each do |method|
433 458

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.