【问题标题】:Link_to action in controller rails 5控制器导轨 5 中的 Link_to 操作
【发布时间】:2017-08-23 08:47:27
【问题描述】:

我在控制器系列中有这个动作

 def hello
 end 

带视图 hello.html.erb

 hello world 

在同一个控制器中的索引视图中我有

<%= link_to 'hello',  families_hello_path %>

在我的 routes.erb 中我做了这个

post  'families/hello', to: 'families#hello' 

但是当取消点击你好我有这个错误:

Couldn't find Family with 'id'=hello 

问题出在哪里?

【问题讨论】:

  • 您可以将bundle exec rake routes |grep families 的输出添加到您的问题中吗?
  • 你在找这个吗?
  • families_hello GET /families/hello(.:format)family#hello

标签: ruby-on-rails-5 link-to


【解决方案1】:

找不到具有 'id'=hello 的家庭

绝对是请求不会发送到hello 方法。当您将路由声明为 post 时,您应该在 link_to 中使用 method: :post 将请求发送到 hello 方法

<%= link_to 'hello', families_hello_path, method: :post %>

【讨论】:

    【解决方案2】:

    rails 认为您有类似 /families/:id 的路由,并且您正在对 /families/hello 的 url 执行 GET。所以 rails 认为你的意思是 'hello' 是家庭记录的 id 并转到 show 操作。

    如果您前往终端并运行rake routes |grep families,您将看到您为家庭配置的所有路线,并且能够进行调整,直到获得正确的路线。您还应该注意 http 方法,它告诉您当前配置的 POST,在这种情况下您必须使用

    <%= link_to "hello", families_hello_path, method: :post %>
    

    但如果您不更改 :hello 操作中的数据,正确的解决方案是更改您的 config/routes.rb 文件中的方法以读取

    get '/families/hello', to: 'families#hello' # Note changing 'post' to 'get' in the front.
    

    【讨论】:

    • 如果您正在寻找特定的家庭记录,那么您的路线应该是“/families/:id/hello”
    【解决方案3】:

    您有两种选择来解决此问题: 第一个是更改route.rb文件

    get 'families/hello', to: 'families#hello' 
    

    第二个是改变index的视图

    <%= link_to 'hello',  families_hello_path, method: :post %>
    

    我更喜欢第一个选项,因为将方法设置为 GET 请求以显示 hello world 页面更符合逻辑,但是这两个选项仍然有效。

    【讨论】:

    • 能否提供给我们完整的 route.rb 文件?
    • 获取 'welcome/index' 资源 :purchases 资源 :customers 资源 :sales 资源 :products 资源 :users root 'welcome#index' post 'sales/add_produit', to: 'sales#add_produit' post 'purchases/add_produit',至:'purchases#add_produit' 获取 'contacts/:id/del_role',至:'contacts#del_role' 获取'families/hello',至:'families#hello' 发布 'contacts/add_role' , to: 'contacts#add_role' get 'sales/:id/delete_produit/:product_id' , to: 'sales#delete_produit' get 'purchases/:id/delete_produit/:product_id', to: 'purchases#delete_produit'跨度>
    • 我想我发现了你的问题,即你的控制器中有类似before_action :set_family 的东西会导致这个问题,如果是这样你可以用before_action :set_family, except: [:hello] 修复它,我希望这对你有帮助.
    • 谢谢你的回答,但我以前做过,我做过这个并且正在工作 " “但只有当我点击你好......并且如果我想点击你好并打开另一个窗口我会遇到同样的错误!!!我认为资源的问题??
    猜你喜欢
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多