开发者

Overwriting data to the model

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 eve开发者_开发知识库rytime. Is there any method in model to update the data or overwrite?

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


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.


Use create_or_update instead of create.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜