【发布时间】:2020-01-15 14:23:45
【问题描述】:
Rails 新手。这个问题很可能是由于我对路由的工作原理有误解但不确定。我的小程序与 Ruby on Rails 在线初学者指南教程中的 Articles 博客示例相同。
我想要做的就是在show.html.erb 文件中有一个按钮/链接,它将我重定向到另一个 url,但我需要访问文章 ID 来访问 url,以便从中获取 title那个文章对象。
在articles_controller.rb 我有:
def join
@article = Article.find(params[:id]) --->getting error, cant find Article without ID
redirect_to(**irrelevant code**))
end
在 show.html.erb 我有:
<%= link_to "Click here", {method: 'get', :controller => "articles", :action => "join"}
在 routes.db 我有:
get '/articles/join', to: 'articles#join'
我收到了错误 ActiveRecord::RecordNotFound in ArticlesController#join 找不到没有 ID 的文章
为什么这不适用于我的加入方法?为什么 params[:id] 中的 id 只能在其他 CRUD 操作中提取?
谢谢
【问题讨论】:
-
您似乎没有从您的 html 发送参数
id。你的加入方法如何知道你想得到什么文章?所以你的params[:id]是空的。尝试打印它,你会看到。 -
你是对的,谢谢!!
-
您还可以将路由更改为
get '/articles/:id/join', to: 'articles#join',以确保路径本身需要 id。
标签: ruby-on-rails ruby activerecord