控制器导轨中的Link_to动作5

时间:2017-08-23 08:47:28

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

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

 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 

问题出在哪里?

3 个答案:

答案 0 :(得分:1)

  

无法找到'id'= hello

的家庭

肯定请求不会hello方法。当您将路线声明为帖子时,您应该使用method: :post中的link_to将请求发送到hello方法

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

答案 1 :(得分:0)

这里rails认为你有一个像/ families /:id这样的路由,你正在对/ families / hello的URL做一个GET。所以铁路认为你的意思是“你好”#39;是家庭记录的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.

答案 2 :(得分:0)

您有两种方法可以解决此问题: 第一个是更改route.rb文件

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

第二个是改变索引的视图

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

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

相关问题