首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的控制器在新的之后调用更新,而不是创建

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

Stack Overflow用户
提问于 2012-11-28 10:10:19
回答 1查看 69关注 0票数 1

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

我有。

/config/routes.rb:

代码语言:javascript
复制
Testivate::Application.routes.draw do
  resources :heuristics do
    resources :variants do
      resources :cycles
    end
  end
end

/app/models/heuristics.rb:

代码语言:javascript
复制
class Heuristic < ActiveRecord::Base
  has_many :variants
  has_many :cycles, :through => :variants
end

/app/models/variants.rb:

代码语言:javascript
复制
class Variant < ActiveRecord::Base
  belongs_to :heuristic
  has_many :cycles
end

/app/models/cycles.rb:

代码语言:javascript
复制
class Cycle < ActiveRecord::Base
  belongs_to :variant
end

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

代码语言:javascript
复制
%h1 New Cycle
= render 'form'

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

代码语言:javascript
复制
= simple_form_for [@heuristic, @variant, @cycle] do |f|
  = f.button :submit

/app/controllers/cycles_controller.rb:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-28 10:13:39

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

代码语言:javascript
复制
@cycle = @variant.cycles.create

应该是这样:

代码语言:javascript
复制
@cycle = @variant.cycles.build

当您调用create时,记录将被保存。在医生里:

Collection.build(属性= {},…) 返回一个或多个集合类型的新对象,这些对象已使用属性实例化并通过外键链接到此对象,但尚未保存。 Collection.create(属性= {}) 返回集合类型的新对象,该对象已被属性实例化,通过外键链接到此对象,并且已保存(如果已通过验证)。注意:只有当基本模型已经存在于DB中时才能工作,而不是如果它是一个新的(未保存的)记录!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13602585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档