hashid-rails icon indicating copy to clipboard operation
hashid-rails copied to clipboard

#find through non-hashid parent association does not work

Open jcypret opened this issue 5 years ago • 5 comments

If you have a has_many association where the parent does not use hashids, find through the association doesn't return the associated record. I added a failing test case to demonstrate.

It seems that to solve this, apart from overriding .find on the model class, we would have to override ActiveRecord::Associations::CollectionProxy's #find method.

Originally posted by @ahawrylak in https://github.com/jcypret/hashid-rails/pull/55#issuecomment-435420302

jcypret avatar May 25 '19 23:05 jcypret

this is a real issue for me too.

geekdeepak avatar Apr 05 '20 16:04 geekdeepak

can this not be fixed? it's a big issue :(

jacobperia avatar Jan 03 '22 21:01 jacobperia

I just ran into this as well. What should the work around be for this?

jtoy avatar Nov 22 '22 21:11 jtoy

@jtoy A workaround is to use find_by_hashid. For example:

post.comments.find_by_hashid(comment.hashid)

But it's much clunkier.

airblade avatar May 26 '23 15:05 airblade

Another workaround is to extend the association explicitly:

class Post
  has_many :comments do
    def find(*)
      find_by_hashid(*)
    end
  end
end

I have been trying to figure out how to extend the association automatically. Starting from the model with the hashid (Comment, in this case) you can get its belong-to associations via Comment.reflect_on_all_associations(:belongs_to), and get their inverses (if you have specified the inverse on the belongs_to associations) via .map(&:inverse_of), which are the has-many reflections (e.g. Post's has-many reflection for its comments association). But I don't know how to get from there to the association proxy (post.comments) in order to include/extend it with the behaviour we want.

airblade avatar May 31 '23 12:05 airblade