How to run a rails model in shell? - ruby-on-rails-3

e.g. I have a model Student:
class Student < ActiveRecord::Base
def self.do_something
ss=Student.find_by_sex "m"
ss.each do |s|
s.blah
s.save
end
end
end
I can do this:
$ rails c
Loading development environment (Rails 3.0.4)
ruby-1.9.2-p180 :001 > Student.do_something
Now, I want a cronjob for this, How do I run above command without (rails c), so I can:
$ ruby student.rb
And get the same result? (I have gems: "mechanize", "hpricot", "to_lang" used in this model)
Thanks!

Maybe you should take look at gem whenever. If you don't want to use it, you shoud try to use rails runner:
/great/path/to/my/application/script/rails runner "Student.do_something"

Related

how do i target a seeds.rb in an engine to avoid seeding my entire app?

My project is on Rails 3.2 and refinerycms v 2.0.10
I just generated a new engine and and ran my bundle and rails generate commands, and my migration. Now, per the docs, I need to run db:seed but I don't want to execute a db:seed at the app level because I have several other engines and I don't want to re-seed them.
it is related to this question:
Rails engine / How to use seed?
but the answer there is to run db:seed at the app level.
So how would I say something like rake myNewEngine:db:seed ? I know it can be done but my google fu is apparently too weak to dredge it up.
You can just generate your own rake task. Create a your_engine.rake file and make sure it is loaded in your Rakefile.
namespace :your_engine do
namespace :db do
task :seed do
YourEngine::Engine.load_seed
end
end
end
Edit the YOUR_ENGINE/lib/tasks/YOUR_ENGINE_tasks.rake
namespace :db do
namespace :YOUR_ENGINE do
desc "loads all seeds in db/seeds.rb"
task :seeds => :environment do
YOUR_ENGINE::Engine.load_seed
end
namespace :seed do
Dir[Rails.root.join('YOUR_ENGINE', 'db', 'seeds', '*.rb')].each do |filename|
task_name = File.basename(filename, '.rb')
desc "Seed " task_name ", based on the file with the same name in `db/seeds/*.rb`"
task task_name.to_sym => :environment do
load(filename) if File.exist?(filename)
end
end
end
end
end
then in your main app you can execute your custom seeds commands, executing any seed file individually
$rake -T | grep YOUR_ENGINE
rake db:YOUR_ENGINE:seed:seed1 # Seed seed1, based on the file with the same name in `db/seeds/*.rb`
rake db:YOUR_ENGINE:seeds # loads all seeds in db/seeds.rb

populate database using irb

Rails 3.2.3
My need is populating a database using an easiest way.
So I created a model
rails g model MyModelName title:string, another_title:string, description:text
Now I'm trying to populate a database some data using irb
mm = MyModelName.create :title =>'title1', :another_title=>'fdfds', :description =>'desc1 fdsfds'
But here is an error
NameError: uninitialized constant MyModelName
from (irb):4
from /home/alex/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'
How do I solve it?
Have you run rake db:migrate yet?
Are you using rails console?

Rails 3.1, why I get ActiveRecord::UnknownAttributeError: unknown attribute in spec test?

I am trying to create a Student record in a test, like this:
student= Student.create!(:work_phone => "1234567890")
but I get this error:
ActiveRecord::UnknownAttributeError: unknown attribute: work_phone
However, work_phone is defined in the Student model, and migrated.
Here is the Studentmodel:
class Student < ActiveRecord::Base
validates_length_of :work_phone, :is => 10, :message => 'must be 10 digits, excluding special characters such as spaces and dashes. No extension or country code allowed.', :if => Proc.new{|o| !o.work_phone.blank?}
attr_accessible:work_phone
end
Any idea?
Are you getting this error only in your test environment. More specifically, when you run tests using
rake spec
This could be happening becase you have not run your migrations on your test environments.
You can either do,
rake db:migrate RAILS_ENV=test
or after having having run migrations on your development like below.
rake db:migrate
rake db:test:prepare
Only adding attr_accessor:work_phone to model also works.

Accessing custom helper methods in rails 3 migrations

In rails 2 I had a lib/migration_helpers.rb file with methods for setting and dropping foreign keys in the db.
These methods were available in self.up and self.down in migration files by adding in the migration file
require 'migration_helpers'
at the top, and
extend MigrationHelpers
immediately after the class statement.
In rails 3 this does not work, and if i try to run a migration using set_foreign_key method from migration_helpers.rb the following error is thrown:
== AddFkToArticles: migrating ================================================
-- set_foreign_key("articles", "book_id", "books")
rake aborted!
An error has occurred, this and all later migrations canceled:
undefined method `set_foreign_key' for #<AddFkToArticles:0x000001034a1f38>
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
I already checked that in config/application.rb the autoload path is set to include lib.
The file is effectively required, because if i comment out the require statement then rails whines about the missing 'migration_helpers' file.
I suspect this is a scoping problem (rails 2 used "def self.up", rails 3 uses "def change")
but cannot imagine how to solve the problem (by now I simply copied the code in the migration file, just to check that it does what it should do).
Francesco
I don't know what exactly you're trying to accomplish but here's some code that might give you a clue.
## lib/test_helper.rb
module TestHelper
def my_table_name
return :mytable
end
end
And then the migration:
## db/migrate/test_migration.rb
include TestHelper
class TestMigration < ActiveRecord::Migration
def self.up
create_table my_table_name
end
def self.down
drop_table my_table_name
end
end
Including this helper inside the Migration class doesn't work so it should be outside.

FactoryGirl + RSpec + Rails 3 'undefined method <attribute>='

I'm fairly new to rails and TDD (as will no doubt be obvious from my post) and am having a hard time wrapping my brain around Rspec and FactoryGirl.
I'm using Rails 3, rspec and factory girl:
gem 'rails', '3.0.3'
# ...
gem 'rspec-rails', '~>2.4.0'
gem 'factory_girl_rails'
I have a user model that I've been successfully running tests on during development, but then needed to add an attribute to, called "source". It's for determining where the user record originally came from (local vs LDAP).
In my factories.rb file, I have several factories defined, that look something like the following:
# An alumnus account tied to LDAP
Factory.define :alumnus, :class => User do |f|
f.first_name "Mickey"
f.last_name "Mouse"
f.username "mickeymouse"
f.password "strongpassword"
f.source "directory"
end
I have a macro defined (that's been working up until now) that looks like this:
def login(user)
before(:each) do
sign_out :user
sign_in Factory.create(user)
end
end
I'm calling it in multiple specs like so (example from users_controller_spec.rb):
describe "for non-admins or managers" do
login(:alumnus)
it "should deny access" do
get :index
response.should redirect_to(destroy_user_session_path)
end
end
If I don't specify the "source" attribute, everything works OK, but as soon as I do, I get an error like so when running the test
12) UsersController for non-admins or managers should deny access
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `source=' for #<User:0x00000100e256c0>
I can access the attribute no problem from the rails console and the app itself, and it's listed in my attr_accessible in the user model. It's almost as though Rspec is seeing an old version of my model and not recognizing that I've added an attribute to it. But if I put the following line into my user model, the error disappears
attr_accessor :source
... which indicates to me that it is actually looking at the correct model.
Help!
How about running this?
rake db:test:load
[If you added a new attribute you'd need to migrate it to the test database.]
if you don't use schema.rb (e.g. you have set config.active_record.schema_format = :sql)
you should run
rake db:test:prepare