Rails nested routing + minor editing does not work

I would like to use some routing as follows:

resources :customers do
  resources :electricity_counters, :shallow => true do
    resources :electricity_bills, :shallow => true
  end
end

Creating electric_counter works fine, but editing doesn't work properly. If I visit electric_counters / 1 / edit, I get only empty fields and all my data is missing.

My _form.html.erb for this starts as

<%= form_for([@customer, @customer.electricity_counters.build]) do |f| %>

and controller methods for new and editing look like this:

# GET customers/1/electricity_counters/new
  def new
    @customer = Customer.find(params[:customer_id])
    @electricity_counter = @customer.electricity_counters.build
  end

  # GET /electricity_counters/1/edit
  def edit
    @electricity_counter = ElectricityCounter.find(params[:id])
    @customer = @electricity_counter.customer
  end

In debugging, it seems that my @customer variable is not set correctly .. but maybe I'm just dumb to use the aptana debugger;)

The electric_counter model has a client relationship:

belongs_to :customer

So what am I doing wrong?

+5
source share
1 answer

Your problem is on this line.

<%= form_for([@customer, @customer.electricity_counters.build]) do |f| %>

electricity_counter , . .

_form partial , , form path. - :

def new
  @customer = Customer.find(params[:customer_id])
  @electricity_counter = @customer.electricity_counters.build
  @path = [@customer, @electricity_counter]
end

def edit
  @electricity_counter = ElectricityCounter.find(params[:id])
  @customer = @electricity_counter.customer
  @path = @electricity_counter
end

<%= form_for(@path) do |f| %>

routes.rb ,

resources :customers, :shallow => true do
  resources :electricity_counters, :shallow => true do
    resources :electricity_bills
  end
end
+16

All Articles