当模型单数和复数名称相同时(例如设备、物种),rails 链接路径和路由错误

2024-01-31

<%= link_to t('.new', :default => t("helpers.links.new")), new_equipment_path, :class => 'btn btn-primary' %>

我在视图中有上述代码,但单击链接时出现以下错误:No route matches {:action=>"show", :controller=>"equipment"}

我的路线文件包含:

resources :equipment

resources :workouts

match ':controller(/:action(/:id))(.:format)'

为什么它试图访问显示操作?

以下是我的路线中的条目:

   equipment_index GET        /equipment(.:format)                   equipment#index
                   POST       /equipment(.:format)                   equipment#create
     new_equipment GET        /equipment/new(.:format)               equipment#new
    edit_equipment GET        /equipment/:id/edit(.:format)          equipment#edit
         equipment GET        /equipment/:id(.:format)               equipment#show
                   PUT        /equipment/:id(.:format)               equipment#update
                   DELETE     /equipment/:id(.:format)               equipment#destroy

这个问题有之前出现过 http://comments.gmane.org/gmane.comp.lang.ruby.rails/237541并且与 Rails 脚手架如何为具有“equipment”(单数和复数)名称的模型生成 new.html.erb 文件有关。

如果您检查form_for在 new.html.erb 文件中你会看到equipment_path在底部的 link_to 中。对于这些具有单数==复数名称的模型,指的是实际上用于show操作,因此您的错误消息。

建议通常是“如果可以的话,避免使用这样的模型名称”,或者涉及对 config/initializers/inflections.rb 文件进行一些修改以强制使用复数版本的模型名称。当然,最终你会得到一个应用程序,其中对模型的引用听起来很奇怪:“设备”不太好用(后来有人会“修复”它,再次把事情搞砸)。

为了保持模型名称在语法上正确,您需要修复 form_for 即:

<% form_for(@equipment, :url=> {:action=>'create'}) do |f| %>

和 link_to:

<%= link_to 'Back', equipment_index_path %>

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当模型单数和复数名称相同时(例如设备、物种),rails 链接路径和路由错误 的相关文章

随机推荐