Paperclip upload image via console

On July 22, 2012, in Technical, by Sanchit Garg

It is very easy to associate an image with a model using ruby console, given you are associating image to the model using paperclip.
Here is what you are gonna do

file = open url //Ruby will fetch the image using HTTP on your server = file // User model uses paperclip to associate photo. This will do the trick

Don’t want to use multipart at client side and still want to associate image to the the model using paperclip? You can do a simple binary upload from the client and handle it at server using following commands

uploaded_io = params[:photo][:data] //read data in binary format uploaded by client/browser
name=params[:photo][:filename] || "uploads.jpg" //file-name
base_dir = Rails.root.join('public', 'system', 'photos' ) //Make sure you have the right target directory
new_dir = File.join(base_dir,
if !
  Dir.mkdir(new_dir, 0700)
end, name), 'w:ASCII-8BIT') do |file|
  file.write(Base64.decode64(uploaded_io)) //saves file at some temp location on your server

Now that you have file on your server, you can run the first code snippet to read it from the location you just saved the file and associate it with the parent model using paperclip internally.




Rails Tips – Counter Cache (.size vs .count)

On June 28, 2012, in Technical, by Sanchit Garg

* Size (rails function) is more intelligent than count (ruby function)
* Notice that when you counter cache, size makes only one call to db as opposed to count which does 2 queries.

1.9.2-p320 :057 > ParentModel.find(5765).childmodel.count
RequestedTrip Load (0.3ms) SELECT `parent_models`.* FROM `parent_models` WHERE (`parent_models`.`id` = 5765) ORDER BY parent_models.created_at desc LIMIT 1
SQL (6.9ms) SELECT COUNT(*) FROM `childmodels` WHERE (`quotes`.requested_trip_id = 5765)
=> 5

1.9.2-p320 :058 > ParentModel.find(5765).childmodel.size
RequestedTrip Load (0.4ms) SELECT `parent_models`.* FROM `parent_models` WHERE (`parent_models`.`id` = 5765) ORDER BY parent_models.created_at desc LIMIT 1
=> 5

You can view all queries to db for commands in rails console by redirecting the logs using following commands:

ActiveRecord::Base.logger =




Mobile Marketing

On June 16, 2011, in Marketing, by Sanchit Garg

This blog is for marketing novices to demonstrate how effective is mobile marketing with some numbers.

Best rate one can get for sending SMS in India – 8 paise per SMS for minimum of 1 lakh SMS. In this case database of phone numbers is provided by the service provider. We did our tie up with Cell Next and they have further tie ups with Airtel, Tata, etc. to send SMS. They promised to send 1 lakh SMS and provide us reports that they were sent. We were told to verify this by calling random 10 numbers in the list and verify.

Time for facts:

  • Total cost for SMS campaign = 8000 + 10.3% tax = 9000 INR
  • Approx calls expected from SMS receivers when the offer sent to them (my ad, or creative) is
    • V. Good = 200 (for e.g. when my ad is say: “trip to Rishikesh in 80% discount”)
    • Good = 100 (for e.g. when my ad is say: “go to Rishikesh for a fabulous trip. Get great deals!”)
    • ok = 50 (for e.g. when my ad is say: “go to Rishikesh for a fabulous trip.”)
  • Remaining statistics in a tabular format (Google adwords vs Mobile marketing)
  • Creative Quality Cool Good ok
    1. Expected Calls 200 100 50
    2. Approx Website Hits 50 30 10
    3. Cost per Lead(INR) (1+2/total Cost) 50 90 180
    Google Adword Costs per Hit 40 50 70


  • Google adwords turn out to be a clear winner against mobile marketing for online websites. Mobile marketing may be useful in following circumstances
    • You need to target offline customers
    • Target them in a day or very quickly want to spread word among the masses
    • Your business can run on phone and you do not need website hits
  • Targeting possibilities that mobile marketing provides
    • Demographic (you can target one particular city)
    • Income group (This group you can not target in google adwords) Not sure how effective this is in mobile marketing, but they claim it to be effective
    • Service Provider based

Conclusion: Whereas Google provides you much more flexibility and various other options and is a clear winner against mobile marketing, unless you have specific requirements as mentioned above.



Tagged with:  

Sphinx – A Use case with Rails 3

On June 10, 2011, in Technical, by Sanchit Garg

Sphinx is open source search server used for full text search, we have used it with Rails and MySql database.

Why Sphinx:

  • Blazingly fast indexing and searching
  • Variety of Text Processing features which are easy to adapt as per Application.
  • Scalling: It can scale up to millions of queries per day.
  • Performance: Sphinx indexes up to 10-15 MB of text per second per single CPU core.
  • Easy to write Sql Style Queries
  • Grouping and Clustering
  • Distrubuted Searching

Thinking Sphinx: Thinking Sphinx is a Ruby gem which helps us to connect Sphinx with Rails Active Record.
We can attach our models to sphinx through Thinking Sphinx


Suppose we have Model Country with  fields: id, name, about, continent_id, capital, rating_no

class Country < ActiveRecord::Base
has_many :places_to_visits

field: name, country_id

class PlacesToVisit < ActiveRecord::Base
belongs_to :country

We want to have full text search on all fields of Country except id and its places to visit (has many association)

How to Use:
We will write in  Country model

class Country < ActiveRecord::Base
has_many :places_to_visits

define_index do
indexes name, :sortable => true
indexes about
indexes rating_no
indexes capital

indexes places_to_visits(:name), :as => :place, :sortable => true
has continent_id

you can read more about indexing here

Searching example

Suppose we want to search countries with rating between 5 and 10. params[:search], :with => {:rating_no => 5..10}

Here with is used for filtering, it accepts ruby array and ranges

A typical example with some advanced options

:match_mode => :all,
:field_weights => {:name => 20, :about => 10},
:with => {:rating_no => 5..10 },
:conditions => { :continent_id => 1},
:page => params[:page], :per_page => 3)
  • We have provided field weights here so that while searching is applied name will have more priority than about
  • conditions is for full text searching specific attributes, :with is for filtering search results.
  • We use pagination with incorporating :page and :per_page parameters
  • match mode: How the key words will match to the fields
    • :all – all records that has the complete key word will be returned
    • :any – means all records that has any of the keyword will be returned
    • :boolean – we can also use boolean operators with keywords
    • example: ‘India | USA’, :match_mode => :boolean




Protected: First Blood!

On June 5, 2011, in Experiences, Operations, by Sanchit Garg

This content is password protected. To view it please enter your password below:



Tagged with: