Forum: Ruby on Rails understanding path_prefix in restful routes

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
82a578052d304559f15180bdf56555d2?d=identicon&s=25 Tarscher (Guest)
on 2007-06-10 15:48
(Received via mailing list)
Hi all,

I have a hard time understanding path_prefix in restful routes.

My urls should always start with the id of a club since my site is
club oriented eg: where zero is the club

I have
  map.resources :clubs
  map.resources :users, :path_prefix => '/:club'
  map.resources :posts, :path_prefix => '/:club'

I don't see how rails knows what :club is. Do I have to set it
somewhere (in my application controller)?

Concrete I have the following problem:
But when I use <%= link_to "new post", post_url(1) %>
I get an error post_url failed to generate from
{:club=>"1", :controller=>"posts", :action=>"show"}, expected:
{:controller=>"posts", :action=>"show"}, diff: {:club=>"1"}

It seems that :club = 1 when it actualy should be a string (zero)

Many thanks in advance
A887cc76c61e1f4148caacb5f32361d6?d=identicon&s=25 jparker (Guest)
on 2007-06-11 21:31
(Received via mailing list)
When you nest resources, the route helpers that are created for that
resource will expect additional arguments to match the named
parameters provided in the :path_prefix option. So, for example, the
route helper for ClubsController#new would just be new_club_path, but
the route helper for PostsController#new would be new_club_path(:club
=> X) or just new_club_path(X), where X is the parent Club or the
parent Club's ID.

In your example, it looks like you might be using the wrong helper.
Your link_to label is "new post" but the route helper you are using is
for PostsController#show. What you probably want is this: <%= link_to
"new post", new_post_path(1) %>. (The show helper [post_path] will
require two arguments: the parent Club and the existing Post to be
shown. It would be called as post_path(:club => X, :id => Y) or just
post_path(X, Y).)

Note that this just covers how the Club ID gets into the URL and
params[:club]. If you want to work with the actual club from within
any of the actions in UsersController or PostsController, those
actions will need to use params[:club] to look up the actual Club
instance, e.g., Club.find(params[:club]).

This topic is locked and can not be replied to.