Search code examples
ruby-on-railshas-one

Rails `form_with` when having a `has_one` association


Rails assumes that my has_one association is plural. Please take a look at my cide snippet:

My model:

class Order  < ApplicationRecord
  has_one :order_detail
end

My routes.rb:

resources :orders do
  resource :order_detail
end

My views/order_details/new.rb:

...
<%= form_with(model: [@order, @order_detail]) do |form| %>
...
<% end %>

Navigating to localhost:3000/orders/1/order_detail/new. The error I get is this:

undefined method `order_order_details_path' for #<#<Class:0x00007ff9be1b66a0>:0x00007ff9be1b4cd8>
Did you mean?  order_order_detail_path
               order_order_detail_url

I know that the route should evaluate to order_order_detail_path, but the array apparently doesn't do this.

How to fix this?


Solution

  • I ended up and solved it by making the :order_details plural.

    resources :orders do
      resource :order_details
    end
    

    The has_one association will still work in the controller and params.