Skip to content

Commit

Permalink
Merge pull request #191 from vic/find_many_by_id_single_request
Browse files Browse the repository at this point in the history
Fetch many instances by id on a single request.
  • Loading branch information
remi committed Nov 3, 2013
2 parents 1932b90 + dba05a1 commit 7efacf1
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/her/model/paths.rb
Expand Up @@ -94,7 +94,7 @@ def build_request_path(path=nil, parameters={})
unless path.is_a?(String)
parameters = path.try(:with_indifferent_access) || parameters
path =
if parameters.include?(primary_key) && parameters[primary_key]
if parameters.include?(primary_key) && parameters[primary_key] && !parameters[primary_key].kind_of?(Array)
resource_path.dup
else
collection_path.dup
Expand Down
1 change: 1 addition & 0 deletions lib/her/model/relation.rb
Expand Up @@ -84,6 +84,7 @@ def fetch
# # Fetched via GET "/users/1" and GET "/users/2"
def find(*ids)
params = @params.merge(ids.last.is_a?(Hash) ? ids.pop : {})
ids = Array(params[@parent.primary_key]) if params.key?(@parent.primary_key)

results = ids.flatten.compact.uniq.map do |id|
resource = nil
Expand Down
17 changes: 17 additions & 0 deletions spec/model/orm_spec.rb
Expand Up @@ -194,6 +194,7 @@ def friends
builder.adapter :test do |stub|
stub.get("/users/1") { |env| [200, {}, { :id => 1, :age => 42 }.to_json] }
stub.get("/users/2") { |env| [200, {}, { :id => 2, :age => 34 }.to_json] }
stub.get("/users?id[]=1&id[]=2") { |env| [200, {}, [{ :id => 1, :age => 42 }, { :id => 2, :age => 34 }].to_json] }
stub.get("/users?age=42&foo=bar") { |env| [200, {}, [{ :id => 3, :age => 42 }].to_json] }
stub.get("/users?age=42") { |env| [200, {}, [{ :id => 1, :age => 42 }].to_json] }
stub.get("/users?age=40") { |env| [200, {}, [{ :id => 1, :age => 40 }].to_json] }
Expand Down Expand Up @@ -233,6 +234,22 @@ def friends
@users[0].id.should == 1
end

it "handles finding by an array id param of length 2" do
@users = User.find(id: [1, 2])
@users.should be_kind_of(Array)
@users.length.should == 2
@users[0].id.should == 1
@users[1].id.should == 2
end

it 'handles finding with id parameter as an array' do
@users = User.where(id: [1, 2])
@users.should be_kind_of(Array)
@users.length.should == 2
@users[0].id.should == 1
@users[1].id.should == 2
end

it "handles finding with other parameters" do
@users = User.where(:age => 42, :foo => "bar").all
@users.should be_kind_of(Array)
Expand Down

0 comments on commit 7efacf1

Please sign in to comment.