1

If I have a ruby script at the root directory of rails application and I need to access existing Activerecord model which is created inside rails environment. How can I use something like

user = User.new

in my script without establishing a new connection or create a new class.

1 Answer 1

1

There are two common ways to deal with Rails models from the command line:

1) rake tasks

Create a rake task in lib/tasks

# example lib/tasks/foo.rake
desc 'an example task'
task :foo => [:environment] do  
  user = User.new
  ...
end

And call that task from your command line with:

rake foo

2) script runner

Create a method within your application that does the job

# example in app/models/user.rb
class User < ActiveRecord::Base
  ...
  def self.foo
    user = User.new
    ...
  end
end

And call this method from the command line with:

rails runner "User.foo"

I prefer the second way, because it is easier to test and reuse the code.

Sign up to request clarification or add additional context in comments.

1 Comment

did you forget the "def" keyword?

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.