1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-05 16:18:01 +00:00

Add Polymorphic Path Helpers as a rails til

This commit is contained in:
jbranchaud
2017-01-27 14:15:13 -06:00
parent 28ebbb9503
commit dde721bfca
2 changed files with 35 additions and 1 deletions

View File

@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
warrant a full blog post. These are mostly things I learn by pairing with
smart people at [Hashrocket](http://hashrocket.com/).
_497 TILs and counting..._
_498 TILs and counting..._
---
@@ -325,6 +325,7 @@ _497 TILs and counting..._
- [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md)
- [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md)
- [Pretend Generations](rails/pretend-generations.md)
- [Polymorphic Path Helpers](rails/polymorphic-path-helpers.md)
- [Read-Only Models](rails/read-only-models.md)
- [Rescue From](rails/rescue-from.md)
- [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md)

View File

@@ -0,0 +1,33 @@
# Polymorphic Path Helpers
Underlying many of the path helpers that we use day to day when building out
the views in our Rails apps are a set of methods in the
[`ActionDispatch::Routing::PolymorphicRoutes`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html)
module.
The `#polymorphic_path` method given an instance of a model will produce the
relevant show path.
```ruby
> app.polymorphic_path(Article.first)
Article Load (0.5ms) SELECT "articles".* FROM "articles" ORDER BY "articles"."id" ASC LIMIT 1
=> "/articles/2"
```
Given just the model's constant, it will produce the index path.
```ruby
> app.polymorphic_path(Article)
=> "/articles"
```
Additionally, there are variants with `edit_` and `new_` prefixed for
generating the edit and new paths respectively.
```ruby
> app.edit_polymorphic_path(Article.first)
Article Load (0.6ms) SELECT "articles".* FROM "articles" ORDER BY "articles"."id" ASC LIMIT 1
=> "/articles/2/edit"
> app.new_polymorphic_path(Article)
=> "/articles/new"
```