我有一个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时,将创建一个调查并将其保存在数据库中。
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
。
中的create
方法SurveysController
与Survey.create
您可以在控制台中调用的方法无关,同样,create_pre
您SurveysController
不能在Survey
模型上调用已添加的新方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句