如何在Ruby on Rails控制器中创建第二个创建方法



我有一个调查类和典型的CRUD方法,包括一个创建方法。我想创建第二个名为 create_pre 的创建方法,该方法可以创建更细致的调查。

这是我的代码:

  def create #old create survey method
    @survey = Survey.new(survey_params)
    respond_to do |format|
      if @survey.save
        format.html { redirect_to(@survey, :notice => 'Survey was successfully created.') }
        format.xml  { render :xml => @survey, :status => :created, :location => @survey }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @survey.errors, :status => :unprocessable_entity }
      end
    end
  end

和新的:

  def create_pre #new create survey method
    @survey = Survey.new(survey_params)
    respond_to do |format|
      if @survey.save
        format.html { redirect_to(@survey, :notice => 'Survey was successfully created.') }
        format.xml  { render :xml => @survey, :status => :created, :location => @survey }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @survey.errors, :status => :unprocessable_entity }
      end
    end
  end

但是当我尝试从控制台使用新的时,我收到一个错误:

 s = Survey.create_pre name: 'Levi's Pre survey', intervention_id: 165242, template_id: 3
NoMethodError: undefined method `create_pre' for Survey (call 'Survey.connection' to establish a connection):Class
Did you mean?  create
    from /home/levi/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.2.4/lib/active_record/dynamic_matchers.rb:26:in `method_missing'

不知道如何解决这个问题?

当我调用 create 时,会创建一个调查并将其保存在数据库中。

irb(main):022:0* s = Survey.create name: 'Levi's Pre survey', intervention_id: 165242, template_id: 3
  SQL (5.1ms)  USE [evrrprod2012]
  SQL (4.1ms)  BEGIN TRANSACTION
  SQL (6.0ms)  EXEC sp_executesql N'INSERT INTO [surveys] ([name], [intervention_id], [template_id], [created_at], [updated_at]) OUTPUT INSERTED.[id] VALUES (@0, @1, @2, @3, @4)', N'@0 nvarchar(4000), @1 int, @2 int, @3 datetime, @4 datetime', @0 = N'Levi''s Pre survey', @1 = 165242, @2 = 3, @3 = '02-25-2016 13:09:15.37', @4 = '02-25-2016 13:09:15.37'  [["name", "Levi's Pre survey"], ["intervention_id", 165242], ["template_id", 3], ["created_at", Thu, 25 Feb 2016 18:09:15 UTC +00:00], ["updated_at", Thu, 25 Feb 2016 18:09:15 UTC +00:00]]
  SQL (2.9ms)  COMMIT TRANSACTION
=> #<Survey id: 40, template_id: 3, name: "Levi's Pre survey", created_at: "2016-02-25 18:09:15", updated_at: "2016-02-25 18:09:15", intervention_id: 165242, created_by: nil, skip_reason: nil, skipped: nil, label: nil, note: nil, parent_id: nil>

使用create_pre时相同的尝试失败。

Survey.create_pre尝试

Survey类上调用类方法,按照惯例,该类将是一个模型,而不是您的控制器。

更新

只是解决 OP 对他们的问题的新评论和补充。

您添加Survey.create方法与您之前在问题中显示的SurveysController#create方法无关。

您显示的是一个控制器实例方法,您在控制器中自行定义了该方法,用于处理传入请求。您在控制台中调用的 Survey.create 是一个ActiveRecord::Base类方法,在您的 Survey 模型中可用,因为它继承自 ActiveRecord::Base .

SurveysController 中的create方法与可以在控制台中调用Survey.create方法无关,同样,无法在Survey模型上调用已添加到SurveysController的新create_pre方法。

最新更新