问题描述
这是在 application.html.erb
中,它适用于我应用中 95% 的页面:
<% ['usd','eur','aud'].each do |currency| %>
<%= form_with url: {controller: :home,action: :currency_select},method: :post do |currency_form| %>
<%= currency_form.hidden_field :preferred_display_currency,value: currency %>
<%= currency_form.submit currency,class: "btn-info shadow-none" %>
<% end %>
<% end %>
但是当我访问某个视图时,甚至在页面加载之前,它就会出现此错误:
ActionView::Template::Error (No route matches {:action=>"currency_select",:controller=>"users/home"}):
191:
192: <%= form_with url: {controller: :home,method: :post do |currency_form| %>
193: <%= currency_form.hidden_field :preferred_display_currency,value: currency %>
194: <%= currency_form.submit currency,class: "btn-info shadow-none" %>
195: <% end %>
196:
197: <% end %>
我很确定与 :controller=>"users/home"
(它应该只是 :controller=>"home"
)有关
为什么表单突然和控制器混淆了?
解决方法
解决方案 1
运行
rails routes | grep currency
它回来了
currency_select POST /currency_select(.:format)
home#currency_select
现在只需像这样使用 url: currency_select_path
:
<% ['usd','eur','aud'].each do |currency| %>
<%= form_with url: currency_select_path,method: :post do |currency_form| %>
<%= currency_form.hidden_field :preferred_display_currency,value: currency %>
<%= currency_form.submit currency,class: "btn-info shadow-none" %>
<% end %>
<% end %>
解决方案 2
用 :home
替换 "/home"
:
<% ['usd','aud'].each do |currency| %>
<%= form_with url: {controller: "/home",action: :currency_select},class: "btn-info shadow-none" %>
<% end %>
<% end %>
(不完全确定为什么有效,但可以确认它确实有效!)
解决办法
以上两种解决方案是最好的,但解决问题的方法可能是:
<% if !current_page?(edit_user_registration_path) %>
# all existing code
<% end %>
这样它就可以避免在出错的路由上显示表单。这并不理想,而是一种实用的解决方法。