Skip to content

Commit

Permalink
Added count method for associations (#392)
Browse files Browse the repository at this point in the history
* Added count method for associations

only for has_many

* test for through count

* Update associations_spec.cr
  • Loading branch information
confact authored Aug 10, 2020
1 parent 59c9795 commit 4178573
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions spec/associations_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ describe Avram::Model do

post.tags.should eq [tag]
end

it "count through associations" do
tag = TagBox.create
post = PostBox.create
TagBox.create
TaggingBox.new.tag_id(tag.id).post_id(post.id).create

post.tags_count.should eq 1
end
end

describe "has_one" do
Expand Down Expand Up @@ -103,6 +112,13 @@ describe Avram::Model do

LineItemQuery.new.find(item.id).scans.should eq [scan]
end

it "gets amount of records" do
item = LineItemBox.create
ScanBox.new.line_item_id(item.id).create

item.scans_count.should eq 1
end
end

describe "has_many through a join table" do
Expand Down
18 changes: 18 additions & 0 deletions src/avram/associations/has_many.cr
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,24 @@ module Avram::Associations::HasMany
@_preloaded_{{ assoc_name }} || lazy_load_{{ assoc_name }}
end

def {{ assoc_name.id }}_count : Int64
{% if through %}
{{ model }}::BaseQuery
.new
.join_{{ through.id }}
.__yield_where_{{ through.id }} do |through_query|
through_query.{{ foreign_key.id }}(id)
end
.preload_{{ through.id }}
.select_count
{% else %}
{{ model }}::BaseQuery
.new
.{{ foreign_key }}(id)
.select_count
{% end %}
end

private def maybe_lazy_load_{{ assoc_name }} : Array({{ model }})?
if lazy_load_enabled?
lazy_load_{{ assoc_name }}
Expand Down

0 comments on commit 4178573

Please sign in to comment.