ruby-on-railsformserbnested-resources

Why is my nested resource form trying to use a non-existent path method when I've already set the URL?


I have the following routes defined in my application:

resources :users do
  resources :data_sets
end

The form data_sets/new is accessed from the following link:

<%= link_to "New Data Set", new_user_data_set_path(user) %>

The form is defined as such:

<%= form_with model: @data_set, url: [@data_set.author, @data_set] do |form| %>
  <!-- form contents... -->
<% end %>

The form gives the following error upon loading:

Showing .../app/views/data_sets/new.html.erb where line #1 raised:

undefined method `data_sets_path' for #<#<Class:0x00007ffd2d1dcf90>:0x00007ffd292a63d0>

The following parameters were passed:

{ "user_id" => "1" }

Similar questions posted here seem to indicate that defining the URL typically solves problems with nested resource forms, but as you can see I already have. What else is going on here?


Solution

  • The form_with helper build the nested url from the array you passed. But in case of new record, @data_set.author returns nil and the form tries to reach data_sets_path which does not exist.

    If your form is just for the "new" action you can write:

    <%= form_with model: @data_set, url: [:user, @data_set] do |form| %>
    

    If you share the form between "new" and "edit", you can write a condition like that:

    <%= form_with model: @data_set, url: [(@data_set.new_record? ? :user : @data_set.author), @data_set] do |form| %>