【问题标题】:Ruby on Rails: Active::RecordNotFound Couldn't find Article without an IDRuby on Rails:Active::RecordNotFound 找不到没有 ID 的文章
【发布时间】: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


【解决方案1】:

因为您的 join 方法需要文章 ID。需要在link_to传递一篇文章

【讨论】:

    【解决方案2】:

    向控制器添加新操作时,最好在路由中使用资源语法:

    尝试:

    resources :articles do
      member do
        get 'join'
      end
    end
    

    这会给你额外的路线:

    join_article  GET  /articles/:id/join(.format)
    

    这样你就可以使用了:

    <%= link_to 'Click Here', join_article(@article) %>
    

    在你看来。

    【讨论】:

      【解决方案3】:

      在您的示例中,您需要在将您的请求发送到操作join 的链接中传递文章的:id - 当前缺少参数。

      <%= link_to "Click here", {method: 'get', :controller => "articles", :action => "join", :id => @article.id } %>
      

      这应该设置 :id 并使其可以在 articles#join 操作中访问。

      【讨论】:

        【解决方案4】:
        <%= link_to "Click here", {method: 'get', :controller => "articles", :action => "join", id => @article.id} -%>
        
        get '/articles/join/:id', to: 'articles#join'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多