public Method

PolymorphicRoutes.polymorphic_url(record_or_hash_or_array, options = {})

Contents:

Constructs a call to a named RESTful route for the given record and returns the resulting URL string. For example:

polymorphic_url(post)
# calls post_url(post) #=> "http://example.com/posts/1"

Options

  • :action — specifies the action prefix for the named route: :new, :edit or :formatted. Default is no prefix.
  • :routing_type:path or :url (default :url).

Examples

# an Article record
polymorphic_url(record)  #->  article_url(record)

# a Comment record
polymorphic_url(record)  #->  comment_url(record)

# it recognizes new records and maps to the collection
record = Comment.new
polymorphic_url(record)  #->  comments_url()

Source Code

# File action_controller/polymorphic_routes.rb, line 70
def polymorphic_url(record_or_hash_or_array, options = {})
  record    = extract_record(record_or_hash_or_array)
  format    = (options[:action].to_s == "formatted" and record_or_hash_or_array.pop)
  namespace = extract_namespace(record_or_hash_or_array)

  args = case record_or_hash_or_array
    when Hash;  [ record_or_hash_or_array ]
    when Array; record_or_hash_or_array.dup
    else        [ record_or_hash_or_array ]
  end

  args << format if format

  inflection =
    case
    when options[:action].to_s == "new"
      args.pop
      :singular
    when record.respond_to?(:new_record?) && record.new_record?
      args.pop
      :plural
    else
      :singular
    end

  named_route = build_named_route_call(record_or_hash_or_array, namespace, inflection, options)
  send!(named_route, *args)
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.