Question

I have an application in which attr_accessor is being used to keep temporary data for a model which will be passed to a rake task. Seeing there is not a database field for these attributes and they are not being calculated from database data, will the attr_accessor data persist and be available to the rake task? What happens if I need to restart the server - does the data get lost then if it's not saved to database? Or to pull this off, do I need to either save to a temp file or a database field?

Was it helpful?

Solution

I assume you are asking whether data that is stored in attributes of ActiveRecord objects stemming from Web requests will be available when accessing them via a Rake task?

No. They won't. That data won't even be available to the next web request. That data won't even be there if you load the same record twice.

class Thing < ActiveRecord::Base
  attr_accessor :data
end

#try this in script/console
thing = Thing.find(:first)
thing.data = "Something"
thing = Thing.find(:first)

puts thing.data
-> nil

OTHER TIPS

It depends on how you are passing your data to the rake task and why. If your trying to do the work out-of-band with the request, meaning not making the user wait until its complete I recommend taking a look at Ryan's excellent screencast here http://railscasts.com/episodes/128-starling-and-workling to learn about job queues.

If its some other exotic reason you must use rake like this you could pass the data as command line parameters. This depends on how much data, and its complexity, you need to pass as it might get out of hand quickly.

Using Daniel's example from above:

thing = Thing.find(:first) thing.data = "Something"

rake myraketask thing_id=#{thing.id} data=#{thing.data}

Of course it'll be lost, where do you think data goes when it dies? To a data h(e)aven from where it can always return?

I'd like to know what you need the data for, but the ultimate answer is probably that the data belongs into the db, unless it's large binary data such as images, where you should save it in the filesystem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top