1

要在我的应用程序中为客户注册地址,我使用嵌套路由,但是当单击链接注册新地址或编辑现有地址时,系统会显示错误:

#<##Class:0x00007fd1c815fa58>:0x00007fd1d05ef598> 的未定义局部变量或方法“地址”您的意思是?@地址

心地善良的人可以告诉我错误在哪里或缺少什么我还没有看到吗?

这是应用程序代码:

路线.rb

resources :clients do
   resources :addresses
end

模型/地址.rb

class Address < ApplicationRecord
  belongs_to :client
end

模型/clients.rb

class Client < ApplicationRecord
  has_many :addresses
end

控制器/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

视图/地址/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 %>

意见/地址/edit.html.erb

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

意见/地址/共享/_form.html.erb

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

4

1 回答 1

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

根据文档,url 的值是“类似于传递给 url_for 或 link_to 的值”,因此使用数组应该可以工作。

这也适用于浅嵌套,因为数组是压缩的。

于 2020-06-24T01:36:12.180 回答