How to get ActiveRecord and Rails to print SQL to the production log

Ruby posted about 1 month ago by christian

Add to the end of config/environment.rb:

   1  ActiveRecord::Base.logger.level = Logger::DEBUG

Config/environments/production.rb might also work.

Tagged sql, production, activerecord, rails, logging

How to customize Hirb output

Ruby posted 3 months ago by christian

Only print id, created_at and title for FeedItem class:

   1  Hirb.disable
   2    Hirb.enable :output => {
   3      "FeedItem"=>{
   4        :options=>{
   5          :fields=>%w{id created_at title}
   6        }
   7      }
   8    }

Tagged hirb, irb, console, rails

How to seed your database with JSON/YAML data in Rails 2.3.4

Ruby posted 4 months ago by christian

In Rails 2.3.4 there’s a new rake task called db:seed that allows you to seed your database with data. To use it you first need a file called db/seed.rb. In it put the code that creates the ActiveRecord objects your application needs.

You can load and execute SQL from an external file, or plain Ruby objects from YAML or JSON as I’ll show you in this example.

Put this in db/seed.rb:

   1  json = ActiveSupport::JSON.decode(File.read('db/seeds/countries.json'))
   2  
   3  json.each do |a|
   4    Country.create!(a['country'])
   5  end

Next export the data from an existing database by running the following command in the Rails console:

   1  File.open('db/seeds/countries.json', 'w') { |f| f << Country.all.to_json }

Now when you run rake db:seed, Rails will load the countries.json file and insert the data into your database.

Pretty print JSON data

You’ll probably want to pretty print your data if you’re going to manually edit it. This can be done by following the instructions in this snippet

Tagged seed, rails, yaml, json, sql, bootstrap, database

How to fix issues with missing gem specifications

Shell Script (Bash) posted 5 months ago by christian

I was getting this error after unpacking hpricot with gem unpack hpricot. I also tried rake gems:unpack hpricot but it did nothing…

   1  config.gem: Unpacked gem hpricot-0.8.1 in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this. 

The rake gems:refresh_specs command doesn’t work, and appears to have been a temporary workaround, so to fix this error I did this:

   1  cd vendor/gems/hpricot-0.8.1
   2  gem specification hpricot > .specification

I had this issue with Rails 2.3.4.

Tagged hpricot, gem, unpack, rails

How to customize to_json

Ruby posted 5 months ago by christian

   1  def to_json(options = {})
   2    if options.empty?
   3      super :only => [:id, :name]
   4    else
   5      super options
   6    end
   7  end
   8  

Now post.to_json will only include the id and name attributes.

Note that for arrays of objects—at least with Rails 2.3.4—you need use the same parameters on the array.to_json method:

   1  Post.all.to_json :only => [:id, :name]

Tagged to_json, activerecord, rails