colmtuite
colmtuite

Reputation: 4491

Routing to an index page specific to a user

I have a posts model and a users model. Post belong to users. On the users/show page I want to link to this url:

/users/1/posts

On this page, I will display all the posts created by the user.

I've tried things like

users/show

<%= link_to "Posts", posts_path(@user) %>

posts/index

<% @posts.each do |post| %>
  <li>
    <%= link_to post.title, post %>
  </li>
<% end %>

but this is routing to

/posts.1

and displaying all posts belonging to all users.

Upvotes: 1

Views: 90

Answers (2)

PeppyHeppy
PeppyHeppy

Reputation: 1355

The url helper for the link you posted will look like this:

user_posts_path(@user) # => /users/123/posts
user_post_path(@user, @post) # => /users/123/posts/1

In order to do what you want you will have to add the correct route:

resources :users do
  resources :posts
end

Then you can see all available url helpers by running the rake routes task. They might look like this:

users_path GET  /users(.:format)                         users#index
user_path GET  /user/:id(.:format)                       users#show
...
user_posts_path GET  /users/:user_id/posts(.:format)     posts#index
user_post_path  GET  /user/:user_id/posts/:id(.:format)  posts#show
...    

Note that in the tasks_controller, the users id will be accessible from the url with params[:user_id]

You might want to look over the rails guide on nested routing

Upvotes: 1

Max
Max

Reputation: 15985

The correct helper is user_posts_path(@user) This requires you have the post resource nested under your user resource in your routes.

In your posts controller you need this code:

def index
  @user = User.find(params[:user_id])
  @posts = @user.posts
end

Upvotes: 1

Related Questions