【问题标题】:How to link_to user's particular page - nested resources如何链接到用户的特定页面 - 嵌套资源
【发布时间】:2019-08-14 20:57:40
【问题描述】:

我有以下代码:

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

【问题讨论】:

  • 您想要一个指向新图书表单的链接?或者你想要评论中的书籍链接?
  • @demir 所以书单存在于 new_book_path 中(令人困惑,抱歉)。在那个 url 上是一个已经创建的书籍列表。我想在这个用户的评论上点击这个用户的名字去那里。
  • 你能在这个视图中展示你的控制器吗?
  • @Mosaaleb 当然,谢谢。此特定视图是帖子的索引:@posts = Post.all@comment = Comment.new。我要访问的网址是新书:@user = current_user // @book = Book.new

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


【解决方案1】:

1) 在评论中:

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

books_list_path 是列出书籍的路径

2) 在列出图书的行动中(indexnew 行动):

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

3) 在 books/index.html.erb

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

【讨论】:

  • 如果不行,能否分享一下相关模型和视图?
  • 谢谢你。为了澄清,我试图从(A)用户对另一个用户(或该用户)帖子的评论(在 Posts 控制器的 index.html.erb 上)到(B)该用户的书籍列表(在 new.html 上)。图书控制器的 erb)。在每本书 show.html 上都有一个帖子列表,每个帖子都有 cmets。网址是 /books/new(使用设计)。也许这就是麻烦所在?用户的网址没有区别,因为都是书籍/新书。
  • 使用 index 动作列出书籍是正确的。使用 new 操作进行列表是不正确的。你能展示一下这本书的模型吗?
  • 我明白了,谢谢。当然:belongs_to :userhas_many :posts, dependent: :destroy
  • 每条评论都与用户相关。 belongs_to :userbelongs_to :post
猜你喜欢
  • 1970-01-01
  • 2014-05-14
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 2011-09-04
  • 1970-01-01
相关资源
最近更新 更多