Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to map a resource to more than one helper in rails?
    primarykey
    data
    text
    <p>I have a Profile model, which is inherited by a Customer and Vendor model. Profile has_many :posts.</p> <p>When I do</p> <pre><code>form_for [ @profile, @post ] do |f| </code></pre> <p>Instead of callind profile_posts_path, form_for will actually call customer_posts_path or vendor_posts_path.</p> <p>Since I want to have URLs like '/foo', '/bar', where <em>foo</em> and <em>bar</em> are usernames I wrote the routes like this:</p> <pre><code>resources :profiles, path: '/', constraints: { id: /[A-Z0-9\-\+\.]+/i } do resources :posts end resources :customers, path: '/', constraints: { id: /[A-Z0-9\-\+\.]+/i } do resources :posts end resources :vendors, path: '/', constraints: { id: /[A-Z0-9\-\+\.]+/i } do resources :posts end </code></pre> <p>This way all requestes to '/foo' will be handled by the ProfilesController (it's the first in the list) and path helpers will be generated so that form_for will work.</p> <p>However even if it works, this is far from ideal. There is evident repetition. If I need to add another nested resource I would have to add it trice. </p> <p>So I refactored it like this (I know that this is horrible, but it works):</p> <pre><code>profile_block = Proc.new do resources :posts end resources :profiles, path: '/', constraints: { id: /[A-Z0-9\-\+\.]+/i }, &amp;profile_block resources :customer, path: '/', constraints: { id: /[A-Z0-9\-\+\.]+/i }, &amp;profile_block resources :vendor, path: '/', constraints: { id: /[A-Z0-9\-\+\.]+/i }, &amp;profile_block </code></pre> <p>But this is still horrible. What I would really love to have is the <em>as</em> parameter to be an array, so that I could do:</p> <pre><code>resources :profiles, path: '/', constraints: { id: /[A-Z0-9\-\+\.]+/i }, as: [ 'profiles', 'customers', 'vendors' ] do ... end </code></pre> <p>Is it possible to achieve something similar? Everything would be mapped to the same controller. And no repetition is in act. Any way to create named routes without having to call <em>resources</em> or <em>match</em> or anything...</p> <p>Thanks in advance</p> <p><strong>edit:</strong> The relation between posts and profiles might become polymorphic in the near future. So the last solution proposed by AJcodex will break.</p> <p>I find this frustrating, I will probably request this feature for the next rails</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload