1

我是一个 Rails 新手,并且有一个看似微不足道/基本的 Rails 问题。

我有一个链接,我试图在其中传递有关对象的信息:

<% for author in @book.authors %>
  <%= link_to "compute", special_book_path(author) %>

如何访问控制器中的“作者”对象(通过特殊命名路由传递)?

我试过:

@author = @book.authors.find(params[:author])

但出现“找不到没有 ID 的作者”错误。

编辑:解决方案

special_book_path(author_id: author.id)

控制器

params[:author_id]
4

2 回答 2

2

当你设置命名路由时,你设置了一个请求参数名称,通常:id,当你使用时special_book_path(author),这个参数的值设置为author.to_param默认情况下author.send(author.class.primary_key)是正常author.id的,所以可能很简单

@author = Author.find(params[:id])

将工作

于 2013-02-14T16:10:51.087 回答
2
  <%= link_to "compute", special_book_path(author: author) %>

这将只传递作者的 id 而不是作者对象。而且您不能在路线中传递对象。

在控制器中,您可以通过 params[:author] 访问传递的参数

  @author = @book.authors.find(params[:author])
于 2013-02-14T16:13:42.223 回答