find-all with polymorphic association?

I have this:

class Document < ActiveRecord::Base

  belongs_to :documentable, :polymorphic => true

and this:

class Task < ActiveRecord::Base

  has_many :documents, :as => :documentable

This, on Document, doesn't work:

  def self.find_all_by_documentable_id(id)     Document.find_all_by_documentable(id)   end

undefined method `find_all_by_documentable' for Document:Class

I've spent hours googling on polymorphism and find, and everyone just talks about how it just works. Only it doesn't because find_all_by isn't defined for my polymorphic association. I guess I could do

.find("documentable_type = ?, documentable_id = ?"...

but that just seems really crude. Any advice?

Why is Documentable another model? Why is it not a column n the
Document table?

Zach Inglis → Blog — http://www.zachinglis.com → Company — http://www.lt3media.com → Portfolio — http://portfolio.zachinglis.com

There is no documentable field defined on Document but documentable_id, which means you don't need to define your own method, just call Document.find_all_by_documentable_id(some_id). Hope it answers your question.

Val http://revolutiononrails.blogspot.com/

There is a documentable field for most purposes eg I can do

d = Document.find(1) p d.documentable

It seems odd that I don't get find methods to go along with this. Is that really the case?

You could do that without the extra documentable field.

class Document < ActiveRecord::Base

#update documentable to true

def documentable

	update_attributes(:documentable => 1)

end

#update documentable to false

def not_documentable

	update_attributes(:documentable => 0)

end

# check to see if it's true or false

def documentable?

	case self.documentable

	where 0

		"is NOT documentable"

	where 1

		"is documentable"

end

end

Something like that. and only with a documentable field rather than a polymorphic association which I could only presume would be heavier.

Zach Inglis

→ Blog — http://www.zachinglis.com

→ Company — http://www.lt3media.com

→ Portfolio — http://portfolio.zachinglis.com

It's an association, so you don't get find_all_by_documentable for the same reason you don't get find_all_by_normal_belongs_to_association.

In other words, given the class below, you don't get find_all_by_foo. You only get find_all_by_foo_id.

class Bar < ActiveRecord::Base   belongs_to :foo end