Tag Archives: rails

Custom seed files in Ruby on Rails 5 project

For project purpose sometimes we need to create multiple seed files. We can do this by simple creating rake tasks in ruby on rails.

To create a rake task for multiple seed file you can use below code:

# lib/tasks/custom_seed.rake
namespace :db do
  namespace :seed do
    Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].each do |filename|
      task_name = File.basename(filename, '.rb').intern    
      task task_name => :environment do
        load(filename) if File.exist?(filename)
      end
    end
  end
end

Please save this code to lib/tasks/custom_seed.rake file

Now create a folder called seeds inside your db folder: db/seeds

Now you can run any seed file from this folder by simple running below command:

# Name of the file without the .rb extension 
rake db:seed:seed_file_name 

Happy Coding 🙂

Advertisements

Prevent browser page caching

One of my rails application shows problem about browser caching. After destroying all login session page redirect back me to my home page. But when I click my browser back button I still see the login pages.

Here is few solution for that.

Clear Cache/No-Cache :

// Code disables caching by browser. Hence the back browser button
// grayed out and could not causes the Page_Load event to fire
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore(); </pre><p><strong> Use Meta Tag for No-Cache: </strong></p><pre>&lt;meta Http-Equiv="Cache-Control" Content="no-cache"&gt;
&lt;meta Http-Equiv="Pragma" Content="no-cache"&gt;
&lt;meta Http-Equiv="Expires" Content="0"&gt;

Clears Browser History and Redirects URL:

//clears browser history and redirects url
&lt;SCRIPT LANGUAGE="javascript"&gt;
{
     var Backlen=history.length;
     history.go(-Backlen);
     window.location.href=page url
}
&lt;/SCRIPT&gt;

Rails :

Write this code on application controller.

before_filter :set_cache_buster

  def set_cache_buster
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  end