Has many scope
# avo-2
n
quick q, I have a
field :posts, as: :has_many, through: :comments
and I appear to be getting the same
Post
record in the list multiple times if there are multiple comments, can I dedupe this somehow?
l
Hi @narrow-magazine-18722, maybe that's happending because some comments has the same post. In order to fix that issue you can add a scope on the field (https://docs.avohq.io/2.0/associations/has_many.html#scope) Example:
Copy code
ruby
field :posts,
 as: :has_many,
 through: :comments,
 scope: -> { query.distinct }
n
awesome, I thought it would be easy! thanks I'll try it
l
Sure, anytime! I hope it solves your issue
n
Just out of curiosity is there a case where
distinct
is unwanted?
l
That's up to you, is there any case where you want to see duplicated records?
n
I can think of some custom use cases, like for example just adding
distinct
won't surface a count, but to get a count that would require some more custom work
for the standard has many through I think it's probably more often wanted than not
I suppose in a lot of use cases there would be no difference between distinct and not
l
Are you using searchable on that field?
n
Nope - but I am just speaking generally now
distinct
worked perfectly for what I'm currently doing, thank you