为什么我的控制器在新的之后调用更新而不是创建

时间:2012-11-28 10:10:19

标签: ruby-on-rails simple-form

当我转到new_heuristic_variant_cycle_path时,我的应用程序会显示循环的新视图,但表单上的提交按钮显示“更新周期”而不是“创建周期”,当您单击提交按钮时控制器进入寻找更新动作。为什么呢?

我有......

/config/routes.rb:

Testivate::Application.routes.draw do
  resources :heuristics do
    resources :variants do
      resources :cycles
    end
  end
end

/app/models/heuristics.rb:

class Heuristic < ActiveRecord::Base
  has_many :variants
  has_many :cycles, :through => :variants
end

/app/models/variants.rb:

class Variant < ActiveRecord::Base
  belongs_to :heuristic
  has_many :cycles
end

/app/models/cycles.rb:

class Cycle < ActiveRecord::Base
  belongs_to :variant
end

/app/views/cycles/new.html.haml:

%h1 New Cycle
= render 'form'

/app/views/cycles/_form.html.haml:

= simple_form_for [@heuristic, @variant, @cycle] do |f|
  = f.button :submit

/app/controllers/cycles_controller.rb:

class CyclesController < ApplicationController
  def new
    @heuristic = Heuristic.find(params[:heuristic_id])
    @variant = @heuristic.variants.find(params[:variant_id])
    @cycle = @variant.cycles.create
    respond_to do |format|
      format.html # new.html.erb
    end
  end
  def create
    @heuristic = Heuristic.find(params[:heuristic_id])
    @variant = @heuristic.variants.find(params[:variant_id])
    @cycle = @variant.cycles.create(params[:cycle])
    respond_to do |format|
      if @cycle.save
        format.html { redirect_to heuristic_variant_cycles_path(@heuristic, @variant, @cycle), notice: 'Cycle was successfully created.' }
      else
        format.html { render action: "new" }
      end
    end
  end
end

1 个答案:

答案 0 :(得分:2)

在你的控制器中,这行代码是错误的:

@cycle = @variant.cycles.create

应该是这样的:

@cycle = @variant.cycles.build

当您致电create时,会保存记录。在doc:

  

collection.build(attributes = {},...)

     

返回一个或多个集合类型的新对象,这些对象已使用属性进行实例化,并通过外键链接到此对象,但尚未保存。

     

collection.create(attributes = {})

     

返回已使用属性实例化的集合类型的新对象,通过外键链接到此对象,并且已保存(如果它已通过验证)。注意:这仅适用于数据库中已存在基本模型的情况,而不是新的(未保存的)记录!