views:

37

answers:

2

I am using reading a table from Oracle and writing the data to a model using cronjob everymidnight so that it help me caching the data and enhance speed. BUT I am using create method to writing the data in model which create new entries and I get duplicate data in my model everytime. Is there any method in model to update the data or overwrite?

  Model.each do |model|
      p = Model.create model.attributes
      p.save
    end
A: 

Why do you want to save the models? It won't help caching. You should instead profile your application and implement caching techniques like memcached.

But anyways here's code to just read your table:

Model.each {|model| Model.new model.attributes }

Update according to your clarification: Copying from one DB to another without duplication could be done like so (given that Model1 accesses the source DB and Model2 access the destination DB):

Model1.each do |model1|
  model2 = Model2.find_or_initialize_by_id model1.id, model1.attributes
  model2.save!
}

This won't handle deletions, however. You may still want to look into memcached and maybe database sharding. It may also be worth thinking about a master/slave replication on database level where your "slow" database is the master (all database writes go to this) and the slave is the "fast" database (all read go to this). Web applications are usually read bound, so it will help in your case. Rails has support for this, see NewRelic's Scaling Rails Screencast Series about scaling your databases.

hurikhan77
well that will right a new record everytme I run this and that exactly is the issue. I have duplicated evry midnight when it runs.
Fonda
I am not sure how to use memcached in my cache because I am fetching data from a remote database (this is where we have problem this db is too slow to fetch all the data) abd copy it to local database every midnight so that it is faster for users. ANy better solution that anyone can suggest?
Fonda
Ah now it get's clearer... You are working with two DBs.
hurikhan77
A: 

Use create_or_update instead of create.

James