Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add Model.pluck method like ActiveRecord: http://api.rubyonrails.org/…

  • Loading branch information...
commit 441abe20130639e97b38f9ac216af455a24dbba8 1 parent 294dfb5
@huacnlee huacnlee authored durran committed
Showing with 37 additions and 0 deletions.
  1. +12 −0 lib/mongoid/finders.rb
  2. +25 −0 spec/mongoid/finders_spec.rb
View
12 lib/mongoid/finders.rb
@@ -129,6 +129,17 @@ def first
def last
with_default_scope.last
end
+
+ # Pick up values array by a column
+ #
+ # @example Pick up all email from User model
+ # User.pluck(:email)
+ #
+ # @return [ Array ] The all values in column
+ def pluck(column_name)
+ column_name = column_name.to_sym
+ with_default_scope.all.only([column_name]).map(&column_name)
+ end
protected
@@ -144,5 +155,6 @@ def last
def find_or(method, attrs = {}, &block)
where(attrs).first || send(method, attrs, &block)
end
+
end
end
View
25 spec/mongoid/finders_spec.rb
@@ -446,6 +446,31 @@
end
end
end
+
+
+ describe "#pluck" do
+ it "work" do
+ Person.create(title: "Senorita")
+ Person.create(title: "Jason")
+ Person.pluck(:title).should eq(%w(Senorita Jason))
+ end
+
+ context "work with Criteria" do
+ before do
+ Person.create(title: "Senorita")
+ Person.create(title: "Jason", pets: true)
+ Person.create(title: "Tim")
+ end
+
+ it "with where" do
+ Person.where(pets: false).pluck(:title).should eq(%w(Senorita Tim))
+ end
+
+ it "with limit" do
+ Person.where(pets: false).limit(1).pluck(:title).should eq(%w(Senorita))
+ end
+ end
+ end
Origin::Selectable.forwardables.each do |method|
Please sign in to comment.
Something went wrong with that request. Please try again.