Reputation: 2759
I have something defined as a app >model > something.rb
class Something < ActiveRecord::Base
end
Now I want to call this from somewhere else. I read that w/o rails running, there is an ActiveRecord error(calling ActiveRecord as some unnamed variable);
How can I call , say
Something.create (x => y) from a helper file?
Upvotes: 1
Views: 51
Reputation: 37419
There is a nice blogpost which gives you the rundown on how to connect to ActiveRecord without rails.
In a nutshell, you need to require
your AR files, and then call establish_connection
with the correct configuration:
Active record works just fine and dandy without rails, but it needs things to be just so. To start, get the gem and add it to your gemfile. Next, make all of your classes inherit from AR like so:
Then you need to require it in the right places. Initially I was requiring AR from the file containing each class, but this was messy and confusing. So instead I moved to a solution that I’d seen Avi put into the CLI playlister project, which helped clean things up: I made a separate file for the entire environment called environment.rb, and made it do all of the requiring for my min-app. The environment file requires AR, points AR to the database file to use, and then requires each of the models. Then the classes don’t have to require anything.
Upvotes: 1