instance method resolve

Ruby on Rails 7.2.3

Since v5.2.8.1

Available in: v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

resolve(*args, &block)

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.

Parameters

args rest
block block
Source
# File actionpack/lib/action_dispatch/routing/mapper.rb, line 2246
        def resolve(*args, &block)
          unless @scope.root?
            raise RuntimeError, "The resolve method can't be used inside a routes scope block"
          end

          options = args.extract_options!
          args = args.flatten(1)

          args.each do |klass|
            @set.add_polymorphic_mapping(klass, options, &block)
          end
        end

Defined in actionpack/lib/action_dispatch/routing/mapper.rb line 2246 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionDispatch::Routing::Mapper::CustomUrls

Type at least 2 characters to search.

↑↓ navigate · open · esc close