Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_a? fails with single-table inheritance in Rails 3

Object#is_a? is failing in the strangest way in Rails 3. I have single-table-inheritance set up as follows (simplified for brevity):

# resource.rb
class Resource < ActiveRecord::Base
  # blah blah
end

# video.rb
class Video < Resource
  # blah blah
end

In my controller, I have this:

def create
  @resource = Resource.find params[:resource_id]
  logger.info '@resource class: ' + @resource.class.name
  logger.info '@resource superclass: ' + @resource.class.superclass.name
  logger.info '@resource is_a?(Video): ' + @resource.is_a?(Video).inspect
  logger.info '@resource is_a?(Resource): ' + @resource.is_a?(Resource).inspect
  logger.info '@resource is_a?(ActiveRecord::Base): ' + @resource.is_a (ActiveRecord::Base).inspect
  # Do some other stuff
end

Invoking the #create action generates these log results:

@resource class: Video
@resource superclass: Resource
@resource is_a?(Video): true
@resource is_a?(Resource): false
@resource is_a?(ActiveRecord::Base): true

Note that the Video instance is an ActiveRecord::Base, yet it is not a Resource. This is not merely an academic concern. Framework code called from the action uses is_a? to check for a type mismatch, and it raises when it thinks the Video is not a Resource.

Yet in the Rails console, is_a?(Resource) returns true.

What in the world could be going on here?

like image 575
rlkw1024 Avatar asked Dec 07 '10 22:12

rlkw1024


1 Answers

The solution is apparently to restart the Rails server process. I don't know how this error crept in, but it did. And what's more, it has happened on multiple occasions on multiple computers.

So, to anyone else experiencing this problem, just restart your server. Whatever it is, it's ephemeral.

like image 155
rlkw1024 Avatar answered Nov 11 '22 13:11

rlkw1024