ruby-on-rails - 如何链接到用户的特定页面 - 嵌套资源
问题描述
我有以下代码:
<%= 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)在评论中:
<%= 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 %>
推荐阅读
- python - Else 循环在满足其参数时似乎没有触发?
- c++ - 我的解码程序的两个部分没有按预期工作
- ios - 返回 UITableView 的函数会导致 EXC_BAD_ACCESS
- python - pylint W0221 参数不同
- encryption - 大文件公钥和三个用户的更快加密
- python - 如何每隔一段时间将金额增加三倍?
- python - 使用简单的python脚本从经纬度坐标获取海拔
- mocha.js - Mocha Chai Sequelize:我不能让测试失败
- ms-access - 3314 在具有自动完成访问权限的组合框中
- c++ - rand()/RAND_MAX 函数每次打印 1