简体   繁体   English

Rails使用多态模型创建多态网址

[英]rails create polymorphic url with polymorphic models

I have the basic setup: 我有基本的设置:

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

Now in _index.html.erb of my documents view, I want to do the following: 现在,在我的文档视图的_index.html.erb中,我想执行以下操作:

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

where @documentable will either be an instance of Contact or Case. 其中@documentable将是Contact或Case的实例。

I expect the above to generate a url like new_contact_document_path, but instead it just tries to produce a url like new_documents_path. 我希望以上代码会生成一个类似于new_contact_document_path的网址,但它只是尝试生成一个类似于new_documents_path的网址。

What might I be doing wrong? 我可能做错了什么?

Try 尝试

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

Note two differences here from your posted code: 请注意此处与您发布的代码的两个区别:

  1. Use the "prefixed" polymorphic_path helper instead of embedding the new action inside the passed array 使用“前缀” polymorphic_path帮助器,而不是将新操作嵌入传递的数组中
  2. Use Document instead of Document.new , which seems to be the preferred approach 使用Document代替Document.new ,这似乎是首选方法

See the ActionDispatch docs for more details. 有关更多详细信息,请参见ActionDispatch文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM