在 Ruby On Rails 中使用 seeds.rb 中的方法
我正在尝试向我的 seeds.rb 添加一个方法,这样我就不必编写一堆冗长的代码。但是,根据 create_deliverable
方法的位置,我在运行 db:setup
时收到两条错误消息之一。
当方法在调用之前时
耙子中止! 私有方法“create_deliverable”调用 #
当方法在调用之后
耙子中止! # 的未定义方法“create_deliverable”
是否无法使用 seeds.rb 中的方法?我是否以某种方式错误地调用了该方法(我尝试过使用和不使用 self.
进行调用)?
方法
def create_deliverable(complexity, project_phase_id, deliverable_type_id)
Deliverable.create(:name => (0...8).map{65.+(rand(25)).chr}.join,
:size => 2 + rand(6) + rand(6),
:rate => 2 + rand(6) + rand(6),
:deliverable_type_id => deliverable_type_id,
:project_phase_id => project_phase_id,
:complexity => complexity)
end
调用代码
@wf_project.project_phases.each do |phase|
DeliverableType.find_by_lifecycle_phase(phase.lifecycle_phase_id).each do
|type|
self.create_deliverable("Low", type.id, phase.id)
self.create_deliverable("Medium", type.id, phase.id)
self.create_deliverable("High", type.id, phase.id)
end
end
I am trying to add a method to my seeds.rb so that I don't have to write a bunch of verbose code. However, depending on the placement of the create_deliverable
method I get one of two error messages when running db:setup
.
When method is before call
rake aborted!
private method 'create_deliverable' called for #
When method is after call
rake aborted!
undefined method `create_deliverable' for #
Is it not possible to uses methods in seeds.rb? Am I somehow calling the method incorrectly (I've tried calling with and without the self.
)?
Method
def create_deliverable(complexity, project_phase_id, deliverable_type_id)
Deliverable.create(:name => (0...8).map{65.+(rand(25)).chr}.join,
:size => 2 + rand(6) + rand(6),
:rate => 2 + rand(6) + rand(6),
:deliverable_type_id => deliverable_type_id,
:project_phase_id => project_phase_id,
:complexity => complexity)
end
Calling Code
@wf_project.project_phases.each do |phase|
DeliverableType.find_by_lifecycle_phase(phase.lifecycle_phase_id).each do
|type|
self.create_deliverable("Low", type.id, phase.id)
self.create_deliverable("Medium", type.id, phase.id)
self.create_deliverable("High", type.id, phase.id)
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保在调用方法之前定义该方法:
Make sure you define the method before calling it:
如果您要使用
self.
,请在方法定义上使用它,而不是在调用上。据我了解,没有类定义的
.rb
文件在运行时会被包装在匿名 ruby 类中,因此在 self 上定义方法应该可以正常工作。If you're going to use
self.
, use it on the method definition, not the call.It's my understanding that
.rb
files without a class definition get wrapped in an anonymous ruby class when they are run, so defining the method on self should work just fine.在我看来,您将
create_deliverable
方法放置在脚本中的private
访问修饰符之后。将其放在public
之后。Looks to me like you placed your
create_deliverable
method afterprivate
access modifier in your script. Put it afterpublic
.