ruby-on-railsruby-on-rails-5nested-routesform-with

Nested routes - rails 5.2.4 - Undefined local variable or method


To register addresses for clients in my application I am using nested routes, however when clicking on the link to register a new address or to edit an existing address the system presents the error:

undefined local variable or method `address' for #<##Class:0x00007fd1c815fa58>:0x00007fd1d05ef598> Did you mean? @address.

Can someone with a good heart inform me where the error is or what is missing that I haven't been able to see yet?

Here is the application code:

routes.rb

resources :clients do
   resources :addresses
end

models/addresses.rb

class Address < ApplicationRecord
  belongs_to :client
end

models/clients.rb

class Client < ApplicationRecord
  has_many :addresses
end

controllers/addresses_controller.rb

class Backoffice::AddressesController < BackofficeController
  before_action :set_client
  before_action :set_address, only: [:edit, :update, :destroy]

  def new
    @address = @client.addresses.build
  end

  def create
    @address = @client.addresses.build(params_address)
    if @address.save
      redirect_to backoffice_addresses_path, notice: "Endereço cadastrado com sucesso!"
    else
      render :new
    end
  end

  def edit
  end

  def update
    if @address.update(params_address)
      redirect_to backoffice_client_addresses_path(@client), notice: "#{@client.name} alterado com sucesso!"
    else
      render :new
    end
  end


  private

    def set_client
      @client = Client.find(params[:client_id])
    end

    def set_address
      @address = @client.addresses.find(params[:id])
    end

    def params_address
      params.require(:address).permit(:nickname,
                                     :cep,
                                     :street,
                                     :number,
                                     :district,
                                     :city,
                                     :state,
                                     :client_id)
    end
end

views/addresses/index.html.erb

<%= link_to new_backoffice_client_address_path(@client)" do %>
    Novo
<% end %>

<% @client.addresses.each do |address| %>
  <tr>
     <td><%= address.nickname %></td>
     <td> ... </td> 
     <%= link_to edit_backoffice_client_address_path(@client, address) do %>
         Editar
     <% end %>
<% end %>

views/addresses/edit.html.erb

<%= render partial: "addresses/shared/form" %>

views/addresses/shared/_form.html.erb

<%= form_with(model: [@client, address], local: true) do |f| %>
  ...
<% end %>


Solution

  • <%= form_with(model: @address, url: [@client, @address], local: true) do |f| %>
    … 
    <% end %>
    

    According to the docs, the values for url are "Akin to values passed to url_for or link_to", so using an array should work.

    This also works with shallow nesting since the array is compacted.