2012-02-06 57 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