我有一个Survey类和典型的CRUD方法,包括一个create方法。 我想创建一个名为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时,会创建一个调查并保存在db。
中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失败时的相同尝试。
答案 0 :(得分:2)
Survey.create_pre
正在尝试在Survey
类上调用类方法,按照惯例,它将是模型,而不是您的控制器。
只是解决OP的新评论和问题。
您添加的Survey.create
方法与您之前在问题中显示的SurveysController#create
方法无关。
您要显示的是控制器实例方法,您已在控制器中自行定义以处理传入请求。您在控制台中调用的那个Survey.create
是ActiveRecord::Base
类的方法,可以在Survey
模型中使用,因为它继承自ActiveRecord::Base
。
create
中的SurveysController
方法与您在控制台中调用的Survey.create
方法无关,同样也与新的create_pre
方法无关您已添加到SurveysController
的广告无法在Survey
模式上调用。