Rails runner script not working

一个人想着一个人 提交于 2020-01-03 21:11:06

问题


Any ideas why this doesn't work, I get a NoMethodErrorwhen I try and run the code below via rails runner.

Maybe I am calling the rails runner incorrectly, sorry new to Rails!

File location:

/app/scripts/data_import.rb

Command:

rails runner -e development DataImport.say_hi

Error:

undefined method `say_hi' for DataImport:Class (NoMethodError)

Code:

class DataImport

  def say_hi
    puts "hi"
  end

end

回答1:


You are calling an instance method on the class, so it's undefined. Try making your method a class method instead:

class DataImport
  def self.say_hi
    puts "hi"
  end
end



回答2:


Change it to

class DataImport
  def self.say_hi
    puts "hi"
  end
end

Since you're accessing it as a class method and not a method on an instance of the class, you need the self to declare the method as a class method.




回答3:


An alternative to the already mentioned transformation of the instance method into a method of the singleton class is to create an object of the existing class and call the instance method in your runner:

rails runner -e development "import = DataImport.new; import.say_hi"



回答4:


The answer is, Many friends already Posted that.

class DataImport
  def self.say_hi
   puts "hi"
  end
end

And the reason is, If you have a class and method without self. , You can't call the class like ClassName.method. You can call like this If only the method is a self method of that class.

Otherwise you can call like ClassName.new.method.

In your Problem, You can call like

DataImport.new.say_hi

And the Class remains the same as you written.



来源:https://stackoverflow.com/questions/5053515/rails-runner-script-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!