Skip to content

Commit

Permalink
Merge pull request #2 from khiav223577/fix/has_one
Browse files Browse the repository at this point in the history
The result of has_one association should not be array
  • Loading branch information
khiav223577 committed Mar 6, 2017
2 parents 80ab5a9 + a161b74 commit 46b6045
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
8 changes: 6 additions & 2 deletions lib/deep_pluck/model.rb
Expand Up @@ -60,12 +60,16 @@ def set_includes_data(parent, children_store_name, model, order_by = nil)
s[children_store_name] = children_hash[id]
}
else #Child.where(:parent_id => parent.pluck(:id))
parent.each{|s| s[children_store_name] = [] }
parent.each{|s| s[children_store_name] = [] } if reflect.collection?
parent_hash = Hash[parent.map{|s| [s["id"], s]}]
children = model.load_data{|relaction| relaction.where(reflect.foreign_key => parent.map{|s| s["id"]}.uniq.compact).order(order_by) }
children.each{|s|
next if (id = s[reflect.foreign_key]) == nil
parent_hash[id][children_store_name] << s
if reflect.collection?
parent_hash[id][children_store_name] << s
else
parent_hash[id][children_store_name] = s
end
}
end
return children
Expand Down
19 changes: 13 additions & 6 deletions test/deep_pluck_test.rb
Expand Up @@ -9,25 +9,32 @@ def test_that_it_has_a_version_number
refute_nil ::DeepPluck::VERSION
end

def test_pluck_with_1_level_deep
def test_1_level_deep
assert_equal [
{'name' => 'John'},
{'name' => 'Pearl'},
], User.where(:name => %w(John Pearl)).deep_pluck(:name)
end

def test_pluck_with_2_level_deep
def test_2_level_deep
assert_equal [
{'name' => 'Pearl' , :posts => [{'name' => "post4"}, {'name' => "post5"}]},
{'name' => 'Kathenrie', :posts => [{'name' => "post6"}]},
], User.where(:name => %w(Pearl Kathenrie)).deep_pluck(:name, :posts => [:name])
assert_equal [
{'name' => 'John' , :contact => [{'address' => "John's Home"}]},
{'name' => 'Pearl', :contact => [{'address' => "Pearl's Home"}]},
], User.where(:name => %w(John Pearl)).deep_pluck(:name, :contact => [:address])
{'name' => 'John' , :contact => {'address' => "John's Home"}},
{'name' => 'Pearl', :contact => {'address' => "Pearl's Home"}},
], User.where(:name => %w(John Pearl)).deep_pluck(:name, :contact => :address)
end

def test_pluck_with_2_level_deep_and_reverse_association
def test_two_associations
assert_equal [
{'name' => 'Pearl' , :posts => [{'name' => "post4"}, {'name' => "post5"}], :contact => {'address' => "Pearl's Home"}},
{'name' => 'Kathenrie', :posts => [{'name' => "post6"}], :contact => {'address' => "Kathenrie's Home"}},
], User.where(:name => %w(Pearl Kathenrie)).deep_pluck(:name, :contact => :address, :posts => :name)
end

def test_2_level_deep_and_reverse_association
assert_equal [
{'name' => 'post4', :user => {'name' => "Pearl"}},
{'name' => 'post5', :user => {'name' => "Pearl"}},
Expand Down

0 comments on commit 46b6045

Please sign in to comment.