polymorphic_path for custom collection route

时间秒杀一切 提交于 2019-12-06 02:04:56

问题


I have the following route definition:

resources :documents do
  collection do
    post :filter
  end
end

and the following model structure:

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

class User < ActiveRecord::Base
  has_many :documents, :as => :documentable
end

and controller structure:

class DocumentsController < ApplicationController
  def index
    # not important
  end

  def filter
    # not important
  end
end

I can easily in a view say:

polymorphic_path([@user, Document])

to get the path /users/1/documents, but I want to be able to say:

filter_polymorphic_path([@user, Document])

to get the path /users/1/documents/filter, unfortunately, this doesn't work.

Anyone know how I can pull this off without adding the following to my routes, for each of my documentable models:

resources :users do
  resources :documents do
    collection do
      post :filter
    end
  end
end

回答1:


polymorphic_path([@user, Document], :action => 'filter') gives you /users/:user_id/documents/filter.

Also, polymorphic_path([@user, Document], :action => 'filter', :sort_order => 'this-order') gives you /users/:user_id/documents/filter?sort_order=this-order.

I ran into the same problem thinking you can replace the edit in edit_polymorphic_path to whatever method you want.

See: http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html




回答2:


This would do it, and it reads nicely.

polymorphic_path([:filter, @user, Document])

Or these

polymorphic_path([:filter, @user, :documents])
polymorphic_path([:filter, @user, Document.new])

And with a query param

polymorphic_path([:filter, @user, Document], :q => 'keyword')

And, in a view you can also do this:

= link_to "Documents", [[:filter, @user, :documents], :q => 'keyword']


来源:https://stackoverflow.com/questions/6142013/polymorphic-path-for-custom-collection-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!