rails 使用多态模型创建多态 url

rails create polymorphic url with polymorphic models

我有基本设置:

class Document < ActiveRecord::Base
  belongs_to :documentable, polymorphic: true
end

class Contact < ActiveRecord::Base
  has_many :documents, as: :documentable
end

class Case < ActiveRecord::Base
  has_many :documents, as: :documentable
end

现在,在我的文档视图 _index.html.erb 中,我想执行以下操作:

<%= link_to "New Document", polymorphic_path([:new, @documentable, Document.new]) %>

其中 @documentable 将是 Contact 或 Case 的实例。

我希望上面的代码生成 url,如 new_contact_document_path,但它只是试图生成 url,如 new_documents_path。

我可能做错了什么?

尝试

<%= link_to "New Document", new_polymorphic_path([@documentable, Document]) %>

请注意此处与您发布的代码的两个不同之处:

  1. 使用 "prefixed" polymorphic_path 帮助程序而不是将新操作嵌入到传递的数组中
  2. 使用 Document 而不是 Document.new,这似乎是首选方法

有关详细信息,请参阅 the ActionDispatch docs