Skip to content


Avoid RecordNotFound on polymorphic parent loading using :find_by Rails 4 not working #987

guigoliveira opened this Issue · 0 comments

1 participant


Hello guys,

Normally on previous versions of Rails when you have a polymorphic model and you want to load a resource through it, you first need to load all possible parent resources and then you load you resource using :though option. Since you have different models being loaded only one will succeed and the others will fail, to prevent a recordnotfound exception you would normally use the :find_by option with a :find_by_id to prevent the bang, using just :id would instead raise the exception.

def find_resource
  if @options[:singleton] && parent_resource.respond_to?(name)
    if @options[:find_by]
      if resource_base.respond_to? "find_by_#{@options[:find_by]}!"
        resource_base.send("find_by_#{@options[:find_by]}!", id_param)
      elsif resource_base.respond_to? "find_by"
        resource_base.send("find_by", { @options[:find_by].to_sym => id_param })
        resource_base.send(@options[:find_by], id_param)
      adapter.find(resource_base, id_param)

Apparently rails 3 classes did not responded to the "find_by" method, so using :find_by => :find_by_id would match the else clause successfuly avoiding the bang in the first if clause:

        resource_base.send(@options[:find_by], id_param)

Starting a new project using Rails 4.0.2 I noticed after a few moments debugging that rails activerecord classes now do respond to "find_by" method alone. This makes impossible to prevent the exception because if you use :find_by => :id would match the first clause, which has a bang in it. If you use :find_by => :find_by_id won´t match the first one but will instantly match the second, translating into this:

resource_base.send("find_by",{ :find_by_id, 1})

"find_by" runs a where, so this call will result in a field not found exception. Also, you are restricted by the "=>" operator which blocks you from doing something like "id = ?", 1

I hope i´m not missing something here, I don´t like making anyone trouble, this gem is awesome and I truly believe we have an issue here.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.