0

这是在 中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, action: :currency_select}, 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")有关

为什么表单突然对控制器感到困惑?

4

1 回答 1

1

解决方案 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', '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 %>

(不完全确定为什么会这样,但可以确认它确实有效!)

解决方法

上述两种解决方案是最好的,但解决该问题的方法可能是:

<% if !current_page?(edit_user_registration_path) %>
# all existing code
<% end %>

这样,它就可以简单地避免在出错的路线上显示表单。这并不理想,但可以解决实际问题。

于 2021-06-14T06:12:01.920 回答