method

resolve

Importance_2
Ruby on Rails latest stable (v7.1.3.2) - 0 notes - Class: CustomUrls
resolve(*args, &block) public

Define custom polymorphic mappings of models to URLs. This alters the behavior of polymorphic_url and consequently the behavior of link_to and form_for when passed a model instance, e.g:

resource :basket

resolve "Basket" do
  [:basket]
end

This will now generate “/basket” when a Basket instance is passed to link_to or form_for instead of the standard “/baskets/:id”.

NOTE: This custom behavior only applies to simple polymorphic URLs where a single model instance is passed and not more complicated forms, e.g:

# config/routes.rb
resource :profile
namespace :admin do
  resources :users
end

resolve("User") { [:profile] }

# app/views/application/_menu.html.erb
link_to "Profile", @current_user
link_to "Profile", [:admin, @current_user]

The first link_to will generate “/profile” but the second will generate the standard polymorphic URL of “/admin/users/1”.

You can pass options to a polymorphic mapping - the arity for the block needs to be two as the instance is passed as the first argument, e.g:

resolve "Basket", anchor: "items" do |basket, options|
  [:basket, options]
end

This generates the URL “/basket#items” because when the last item in an array passed to polymorphic_url is a hash then it’s treated as options to the URL helper that gets called.

NOTE: The resolve method can’t be used inside of a scope block such as namespace or scope and will raise an error if it detects that it is.

Show source
Register or log in to add new notes.