Rails嵌套路由+浅编辑无法正常工作

kan*_*nix 6 ruby-on-rails

我想使用这样的路由:

resources :customers do
  resources :electricity_counters, :shallow => true do
    resources :electricity_bills, :shallow => true
  end
end
Run Code Online (Sandbox Code Playgroud)

创建electric_counter工作正常,但编辑不能按预期工作..如果我访问electricity_counters/1 /编辑我只会得到空白字段,我的所有数据都丢失了.

我的_form.html.erb就是这样开始的

<%= form_for([@customer, @customer.electricity_counters.build]) do |f| %>
Run Code Online (Sandbox Code Playgroud)

新的和编辑的控制器方法是这样的:

# 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
Run Code Online (Sandbox Code Playgroud)

在调试中似乎是我的@customer变量没有设置正确..但也许我只是愚蠢使用该aptana调试器;)

electric_counter模型与客户的关联设置为:

belongs_to :customer
Run Code Online (Sandbox Code Playgroud)

那么我做错了什么?

Azo*_*olo 16

你的问题是这一行.

<%= form_for([@customer, @customer.electricity_counters.build]) do |f| %>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

形成

<%= form_for(@path) do |f| %>
Run Code Online (Sandbox Code Playgroud)

此外,您还可以routes.rb改变它

resources :customers, :shallow => true do
  resources :electricity_counters, :shallow => true do
    resources :electricity_bills
  end
end
Run Code Online (Sandbox Code Playgroud)