jcypret / hashid-rails

Use Hashids (http://hashids.org/ruby/) in your Rails app ActiveRecord models.
MIT License
349 stars 48 forks source link

#find through non-hashid parent association does not work #61

Open jcypret opened 5 years ago

jcypret commented 5 years ago

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

geekdeepak commented 4 years ago

this is a real issue for me too.

jacobperia commented 2 years ago

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

jtoy commented 1 year ago

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

airblade commented 1 year ago

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

post.comments.find_by_hashid(comment.hashid)

But it's much clunkier.

airblade commented 1 year ago

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.