stevec
stevec

Reputation: 52498

form_with producing wrong controller (only on some routes)?

This is in application.html.erb, and it works on 95% of the pages in my app:

<% ['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 %>

But when I visit a certain view, before the page even loads, it gives this error:

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 %>

I'm pretty sure something to do with :controller=>"users/home" (where it should simply be :controller=>"home")

Why is the form suddenly confused about the controller?

Upvotes: 0

Views: 204

Answers (1)

stevec
stevec

Reputation: 52498

Solution 1

Run

rails routes | grep currency

it returns

currency_select POST   /currency_select(.:format)  
 home#currency_select

Now just use url: currency_select_path like so:

<% ['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 %>

Solution 2

Replace :home with "/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 %>

(not totally sure why that works, but can confirm that it indeed works!)

A work around

The above two solutions are best, but a work around for the problem could be:

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

This way it simply avoids displaying the form on the route that errors. It's not ideal, but a practical work around.

Upvotes: 1

Related Questions