2012-02-06 55 views
5

我想用一些路由這樣的:Rails的嵌套路由+淺編輯工作不

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

創建electricity_counter工作正常,但如預期編輯不工作.. 如果我訪問electricity_counters/1 /編輯我只收到空白字段,我的所有數據都丟失了。

我爲_form.html.erb開始像這樣

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

,併爲新的和編輯控制器方法是這樣的:

# 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 

在調試這似乎是我的@客戶變量沒有設置正確..但也許我只是愚蠢地使用該aptana調試器;)

electric_counter模型與客戶關聯設置:

belongs_to :customer 

那麼我做錯了什麼?

回答

16

你的問題是這條線。

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

它建立一個新的electricity_counter不管你想要做什麼。因爲你正在控制器中處理它。

但既然你想要使用相同的_form部分爲新和編輯你必須能夠改變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 
+0

謝謝:) 但有似乎是其他錯誤..如果我打開編輯,我得到: 'NoMet在Electricity_counters#編輯 未定義的方法'customer_electricity_counter_path'爲#<#Class <0x10cb659d8>:0x10cb61590> – kannix 2012-02-06 17:06:17

+0

您的資源是淺的,您不需要在'customer'前面加上'electricity_counter_path'。但是我認爲你的'routes.rb'已經倒過來了,我會很快地編輯我的答案。 – Azolo 2012-02-06 17:29:23

+0

嗯我修復了routes.rb並將我的form_for方法調用改爲 '<%= form_for @electricity_counter do | f | %>' 修復了編輯..但在此之後,新的路線似乎中斷:( '沒有路線匹配{:format => nil,:controller =>「electricity_counters」}' – kannix 2012-02-06 17:53:03