Schneems
Schneems

Reputation: 15858

Rails automatically pull out resource from nested resources in routes helpers

I have nested resources like so

resources :users do
  resources :widgets
end

When I have @widget, to get a proper routing from my helpers i need to use user_widget_path(@widget.user, @widget) is there any way to tell rails to automatically pull out the user from @widget object? So i could just use user_widget_path(@widget)

Upvotes: 2

Views: 367

Answers (2)

fl00r
fl00r

Reputation: 83680

@apneadiving is totally right. But you can improve a little your approach:

 link_to "user", user_widget_path(@widget.user, @widget)

can be presented shorter:

 link_to "user", [@widget.user, @widget]

UPD

Also you can rewrite user_widget_path as you want:

class ApplicationController < ActionController::Base
  helper_method :user_widget_path
  private
  def user_widget_path(widget)
    super(widget.user, widget)
  end
end

You should also rewrite edit_user_widget_path, new_user_widget_path. And better to wrap it as an external Module.

Upvotes: 2

apneadiving
apneadiving

Reputation: 115541

There is no automatic method to do this. But you could create your own application helper, it's pretty straight.

Upvotes: 2

Related Questions