0

I am trying to modify my database in rails for that I want to write a script that would modify my model accordingly when executed. I have no idea how to create a script and run it using rails console. Please somebody guide me.

Eg -: Suppose i want to write a script that has Model.all written in it and when I execute it using console Model.all should run

2 Answers 2

2

Use Rails tasks instead:

lib/tasks/mytasks.rake

namespace :mytasks do

    desc "This is a Hello world task. All it does it say hello"
    task :hello => :environment do
      puts "Hello!"
    end
end

Then in the console you do:

rake mytasks:hello
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works. But it needs two corrections: (i) the filename must have the extension rake ('mytasks.rake'), (ii) quotation mark after Hello! is missing.
0

One the quick temporary solution adds a new class method to your Model:

class Model
  def self.modify_db
    Model.find_each do |item| 
    end
  end
end

In console just type: Model.modify_db

7 Comments

Yes this can be done, but is there another way... like writing code in some ruby file and execute it from console?
Yes, you can create a file in a lib folder. Define class or module and a function in it.
Too you can write a rake task and it in terminal
I was trying to do that only. In lib -> tasks -> hello.rake ( task :hello => [:environment] do Project.all end ) , then in rails console I wrote rake hello.rake
Rake task need to run in a terminal, not within rails console. rake hello
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.