I’m trying to wrap my head around how to set up this schema with polymorphic associations:
a “Document” has one metadata object, but this can either be “PDFMetaData” or “TXTMetaData”.
My concerns are:
To set up this association, I can do this
class Document
belongs_to :metadata, :polymorphic => true
end
class PDFMetaData
has_one :document, :as => :metadata
end
class TXTMetaData
has_one :document, :as => :metadata
end
This works, but it kind of feels like reverse for me: A document has_one metadata object, not opposite?
Also, I’m really running into problems when trying to create a nested form for my new document. I know I can use fields_for, but how do I know what kind of object it is? (PDFMetaData or TXTMetaData). Do I have to render separate partials depending on what kind of document I have?
I’m afraid that the latter ties in with my first question, and that I’m doing something terribly wrong.
Thanks
Although I can see where you’re coming from about the confusion with arrangement of belongs_to & has_one in this case, the rationale is based on where the foreign_key is in the DB schema. The documents table contains the foreign_key that relates it to the PdfMetaData object thus it wouldn’t make sense to describe the relationship the other way round since there would be no way to have a has_many relationship (how would you store multiple foreign keys in the 1 database row?)
Hopefully that makes sense … but on to the 2nd problem, the solution depends on the list of valid attributes on your
TXTMetaDataandPDFMetaDataclasses. If they have the same attributes (or at least the ones you want available in your form are the same) then you should be okay withand so on
If however you want to expose different attributes then I’d suggest detecting the class of your metadata object and act accordingly e.g.