How to link_to user's particular page - nested resources

154 views Asked by At

I have the following code:

<%= link_to new_book_path(controller: :books, action: 'new', id: comment) %>

#also tried:

<%= link_to new_book_path(comment.user.id) %>
#outputs: undefined id

<%= link_to new_book_path(comment.user_id) %>
#leads to my (logged-in user) book list, not this user's

<%= link_to new_book_path(comment.user) %>
#same

<%= link_to new_book_path(comment) do %>
#same. comment.post.book.user.id also same.

I was wondering how I can get to this particular user's book list through link_to from this user's comment. I keep going to my own.

My routes are:

resources :books do
  resources :posts, shallow: true
end

resources :posts do
  resources :comments, shallow: true
end

resources :users do
  resources :comments, shallow: true 
end
1

There are 1 answers

8
demir On

1) in comment:

<%= link_to comment.user.name, books_list_path(user_id: comment.user.id)

books_list_path is path where books are listed

2) in action where books are listed (index or new action):

class BooksController < ApplicationController
  ..
  def index
    @books = Book.where(user: params[:user_id])
  end
  ..
end

3) in books/index.html.erb

<% @books.each do |book| %>
  <%= book.name %><br>
<% end %>