0
votes

I have a Model (let's call it A) in a Rails project that checks an attribute (let's call it a) with the ActiveRecord::Dirty a_changed? function on before_save. I want to be able to save an instance of A in a Rake task, but simply including :environment isn't cutting it--I'm getting a "no method a_changed? defined on A" message in the Rake task. How do I get ActiveRecord to remember about ActiveRecord::Dirty within a Rake task?

Rails version is 2.3.11

namespace :some_namespace do
  namespace :some_subnamespace do
    desc "This is a Rake Task"
    task :some_taskname, [:some_arg] => [:environment] do |t,arg|
      foo = A.find(11111)
      foo.save #<=== fails with "no method a_changed? defined on A"
    end
  end
end

Since that's a pretty dense bunch of info, here's the breakdown:

  1. I have a model A with an attribute a.
  2. Model A has a before_save trigger defined that calls a_changed?, which is a method added by ActiveRecord::Dirty in the Rails environment. There are no problems calling this from a controller.
  3. In my Rake task, however, the a_changed? call in the before_save trigger causes a NoMethodError exception to be raised, presumably because the [:environment] requirement is not sufficient to include ActiveRecord::Dirty. My question is how to make this not happen (my workaround is to rescue NoMethodError from inside the before_save, which is an obvious hack).
1

1 Answers

0
votes

Looks like your question has already been answered on a previous question asked on StackOverflow.

In order to determine what methods your object has you can do this:

...
desc "This is a Rake Task"
task :some_taskname, [:some_arg] => :environment do |t, args|
  foo = A.find(11111)
  p foo.methods
...

This will print out a list of the available methods. If the array includes :some_attr_changed? (where some_attr is an attribute), then you can be certain that ActiveRecord::Dirty is indeed working fine in the rake task. If those methods don't show up in the array, then your assumptions are correct.