Reputation: 486
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.
Upvotes: 1
Views: 772
Reputation: 106802
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.
Upvotes: 1