如何链接到用户的特定页面-嵌套资源

时间:2019-08-14 20:57:40

标签: ruby-on-rails ruby link-to nested-resources

我有以下代码:

<%= 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.

我想知道如何从该用户的注释中通过link_to到达该特定用户的图书清单。我继续努力。

我的路线是:

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 个答案:

答案 0 :(得分:0)

1)在评论中:

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

books_list_path 是列出书籍的路径

2)在列出图书的地方进行操作(索引操作):

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

中的

3)

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