I would like to use some routing like this:
resources :customers do
  resources :electricity_counters, :shallow => true do
    resources :electricity_bills, :shallow => true
  end
end
Creating a electricity_counter works fine, but edit doesn't work as expected.. If I visit electricity_counters/1/edit I only get blank fields and all my data is missing.
My _form.html.erb for that starts like this
<%= form_for([@customer, @customer.electricity_counters.build]) do |f| %>
and the controller methods for new and edit are 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 debug it seems to be that my @customer variable isn't set right.. but maybe I'm just to stupid to use that aptana debugger;)
The electricity_counter model has the association to a customer set by:
belongs_to :customer
So what am I doing wrong?
Your problem is this line.
<%= form_for([@customer, @customer.electricity_counters.build]) do |f| %>
It builds a new electricity_counter no matter what you want to do. Since you're handling that in the controller.
But since you want to use the same _form partial for both new and edit you have to be able to change the form path. Basically I ended up doing something like this:
Controller
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
<%= form_for(@path) do |f| %>
Also your routes.rb is off change it to this
resources :customers, :shallow => true do
  resources :electricity_counters, :shallow => true do
    resources :electricity_bills
  end
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With