开发者

Rails Polymorphic association + fields_for

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开发者_如何学Python 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 TXTMetaData and PDFMetaData classes. 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 with

fields_for :metadata do |meta_fields|
  meta_fields.text_field :attr
  meta_fields.text_fields :attr2
end

and 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.

meta_obj = document.metadata
fields_for :metadata, meta_obj do |meta_fields|
  if meta_obj.is_a?(PDFMetaData)
    meta_fields.text_field :attr
    meta_fields.text_fiels :attr2
  elsif meta_obj.is_a?(TXTMetaData)
    meta_fields.text_field :other_attr
    meta_fields.text_fiels :other_attr2
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜