首页 > 解决方案 > 如何链接到用户的特定页面 - 嵌套资源

问题描述

我有以下代码:

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

标签: ruby-on-railsrubylink-tonested-resources

解决方案


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

3) 在书籍/index.html.erb中

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

推荐阅读