Donato
Donato

Reputation: 2777

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:

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

where @documentable will either be an instance of Contact or 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.

What might I be doing wrong?

Upvotes: 1

Views: 758

Answers (1)

Todd Agulnick
Todd Agulnick

Reputation: 1995

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
  2. Use Document instead of Document.new, which seems to be the preferred approach

See the ActionDispatch docs for more details.

Upvotes: 3

Related Questions