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

时间:2015-01-03 22:22:06

标签: ruby-on-rails

我有基本设置:

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的实例。

我希望上面生成一个类似new_contact_document_path的url,但它只是尝试生成一个类似new_documents_path的url。

我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试

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

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

  1. 使用&#34;前缀&#34; polymorphic_path helper而不是在传递的数组中嵌入新动作
  2. 使用Document代替Document.new,这似乎是首选方法
  3. 有关详细信息,请参阅the ActionDispatch docs

相关问题