Render a polymorphic partial with optional belongs_to/nested inherited resources (Rails 3.1)
Trying to do something really simple--could someone please provide the correct incantation?
Basically we have Biscuit
optionally nested in User
so we'd like routes like:
/biscuits
/biscuits/1
/users/2/biscuits
/users/2/biscuits/3
etc.
We have views like biscuits/index
which calls a p开发者_运维技巧artial biscuits/_index
to render the list. I'd like to call this same partial from the user's profile view, users/edit
, but I'm unclear on which resource_url helpers to use:
resources :users do
resources :biscuits
end
class BiscuitsController < InheritedResources::Base
belongs_to :user, optional: true
end
users/edit.html.haml:
= render 'biscuits/index', biscuits: @user.biscuits.all
biscuits/_index.html.haml:
- biscuits.each do |biscuit|
%tr
%td= biscuit.title
%td= link_to image_tag(biscuit.file_url(:thumb,:large)), resource_url(biscuit)
%td
= link_to 'Show', resource_url(biscuit)
|
%td
= link_to 'Edit', edit_resource_url(biscuit)
This partial works fine when called from the BiscuitsController
at /users/1/biscuits
, but it bombs with NoMethodError in Users#edit undefined method 'user_url' for #<UsersController>
when called from the UsersController
at /users/1/edit
-- seems the resource_url
refers to the user here not the biscuits collection.
How could I force the resource/collection to be any collection of resources, regardless of the current controller?
What's the better way to do this?
Also, say we override UsersController#collection
and #resource
, are these methods on the UsersController
called if the route invokes the BiscuitsController
via /users/1/biscuits
? Or is only one Controller
per request ever instantiated by Rails?
regarding routes behavior - as far as I know, if you want to use a route both nested and non-nested, you really should define it twice. i.e.
resources :users do
resources :biscuits
end
resources :biscuits
that said, it seems to be considered better practice to nest resources only if there is no sense to access them without nesting. if you leave only the non-nested routes for biscuits it might solve your problem.
regarding resource_url - your references to resource_url and collection methods indicate you are using a plugin or gem, it's hard to know what's going wrong without knowing what plugin you are using especially since it seems to be the source of your problem.
substituting "resource_url" for a helper along the lines of
def nested_resource_path(*args)
args = args.compact
return args[0] if args.size == 1
return args
end
called thus:
nested_resource_path(@user, biscuit) and
nested_resource_path(:edit, @user, biscuit)
where @user is nil when accessing BiscuitsController#index
should work.
chuck in a shallow route, that is:
resources :users, :shallow => true do
resources :biscuits
end
then do rake routes and see if that does the trick
精彩评论