Michael Victor


1,010 Experience
3 Lessons Completed
0 Questions Solved


Is there a guide or best case practise to help people on choosing the best database column names (or even for variables?). I am not really looking at syntactical naming conventions such as snake case, camel case or even singular or plural.

Here is an example from what we faced. We have a column that would indicate that a user would want to become an admin when signing up and based on this triggers would be initiated. Some of the names that we came up with were wants_to_be_admin, intends_to_be_admin, wants_to_administer, potential_admin. These column names seem equivalent, but we would like to standardise the way we come up with these names.

How would you propose to start making this guide/convention in a company? Has this been done before?

Posted in What database should I use?

I would like to create a database to store how often access tokens in my system are being used.

I was thinking of a data model like so -

  • Access Token
  • from (basically I will store this hourly, so this will be the timestamp of teh start of the hour)
  • Number of times used
What would be the ideal database for this? I am conflicted with several choices.

Some more details to help out -

  1. We get around 5k requests per minute, so the DB will have to be quick enough to update that.
  2. We will not often be querying the database, probably only be looking for daily summaries and month end aggregations for accounting and auditing purposes.
  3. We would prefer this to be on AWS as a service, but we can also spin up instances on our own.

Posted in Migrate away from Mandrill?

We've been using PostMark for the past 3-4 months. They give you 25k emails free and another 10k if you send your first transactional email via the API 24 hours post signing up.

We've loved their support as well!

Posted in Compare two active record results along just one column

I have 3 models - Items, Customizations and Property Maps

Property Maps has a polymorphic association with Items and Customizations

The business logic here is, when listing customizations properties -

If the customization does not have any properties, display the item properties in a normal cell
If the customization has properties that are different from the item, display the list of properties in a "customized-cell" class
If the customization has the same properties as that of the item, display the list of properties in a normal cell.
If both, the customization and item have no customization, display a blank cell.
This is my current implementation of the above

- item_array = Array.new
- @item.property_maps.wood_only.each do |property|
    - item_array.push(property.property_id)
- customization_array = Array.new
- customization.property_maps.wood_only.each do ||
    - customization_array.push(property.property_id)
- if customization.property_maps.wood_only.present? && item_array.sort != customization_array.sort
    td.customized-cell = customization.property_maps.wood_only.map {|property| "#{property.property.name}"}.join(', ')
- elsif @item.property_maps.wood_only.present?
                td = @item.property_maps.wood_only.map {|property| "#{property.property.name}"}.join(', ')
            - else 

Is there a way where I can compare the results across a column directly from Active Record? This would save the need for me create new arrays and then compare them.

Posted in Constant Map Filtering

So this is the join that I used --

def  self.find_with_properties property_ids, group_name
  joins(:product_properties).joins('JOIN product_properties '+group_name+' ON '+group_name+'.product_id = products.id  AND '+group_name+'.property_id IN ('+property_ids.to_s.tr('[', '').tr(']', '').tr('"', '') +')')

Posted in Constant Map Filtering

I have two models Product and Product Properties. So, I store the properties for products in the Product Properties model which is associated with another model Properties

How can I implement a scope that finds a product with the properties (A or B or C) AND (X or Y or Z)

Filters I currently have are like so --

`scope :product_type_filter, lambda {|property_id|
  return nil if property_id.blank?
  joins(:product_properties).where('product_properties.property_id IN (?)', property_id).distinct

scope :metal_filter, lambda {|property_id|
  return nil if property_id.blank?
  joins(:product_properties).where('product_properties.property_id IN (?)', property_id).distinct

And product the following SQL -SELECT DISTINCT "products".* FROM "products" INNER JOIN "product_properties" ON "product_properties"."product_id" = "products"."id" AND "product_properties"."deleted_at" IS NULL WHERE "products"."deleted_at" IS NULL AND (product_properties.property_id IN ('504')) AND (product_properties.property_id IN ('520'))

But it doesn't really work since it's looking for a Product Property which has both values 504 and 520, which will never exist.

Would appreciate some help!

Posted in Paperclip - Watermarking for dynamic image sizes

I'm looking to add watermarks to all images that are uploaded to my application. They can be of several sizes and this is where I'm running into trouble.

This is my watermark processor:

module Paperclip
  class Watermark < Processor
    def initialize(file, options = {}, attachment = nil)
      geometry = options[:geometry]
      @file = file
      @crop = geometry[-1,1] == '#'
      @target_geometry = Geometry.parse geometry
      @current_geometry = Geometry.from_file @file
      @convert_options = options[:convert_options]
      @whiny = options[:whiny].nil? ? true : options[:whiny]
      @format = options[:format]
      @watermark_path = options[:watermark_path]
      @position = options[:position].nil? ? "SouthEast" : options[:position]
      @watermark_offset = options[:watermark_offset]
      @overlay = options[:overlay].nil? ? true : false
      @current_format = File.extname(@file.path)
      @basename = File.basename(@file.path, @current_format)
      Rails.logger.info "watermark initialized"

     # Returns true if the +target_geometry+ is meant to crop.
    def crop?

    # Returns true if the image is meant to make use of additional convert options.
    def convert_options?
      not @convert_options.blank?

    # Performs the conversion of the +file+ into a watermark. Returns the Tempfile
    # that contains the new image.

    def make
      Rails.logger.info "watermark make method"
      src = @file
      dst = Tempfile.new([@basename].compact.join("."))

      if @watermark_path.present?
        command = "convert"
        params  = %W['#{fromfile}']
        params += transformation_command
        params += %W['#{@watermark_path}' -gravity #{@position} -composite]
        params << "'#{tofile(dst)}'"
        command = "convert"
        params = ["'#{fromfile}'"]
        params += transformation_command
        params << "'#{tofile(dst)}'"

      Rails.logger.info 'params:' + params.to_s

        Paperclip.run(command, params.join(' '))
      rescue ArgumentError, Cocaine::CommandLineError
        raise Paperclip::Error.new("There was an error processing the watermark for #{@basename}") if @whiny


    def transformation_command
      scale, crop = @current_geometry.transformation_to(@target_geometry, crop?)
      trans = %W[-resize '#{scale}']
      trans += %W[-crop '#{crop}' +repage] if crop
      trans << @convert_options if @convert_options.present?

    def fromfile

    def tofile(destination)

I'm wondering what strategies I can use to get this done or if there are some good gems around I can use.

Things I have thought of

Resizing the watermark image to 10% of the image size before placing it on top of the image (seems the best option right now)
Adding a transparent image with the watermark on the bottom right already taking up 10% of the space. (but this might not really work since I can't for sure specify what kind of aspect ratio is being uploaded)
Model File for reference:

class Picture < ActiveRecord::Base
    belongs_to :picturable, polymorphic: true

    #Gem Functions

    has_attached_file :picture_file,
                        styles: {
                          medium: {
                            processors: [:watermark],
                            geometry:       "268*222",
                            watermark_path: "#{Rails.root}/app/assets/images/watermark.jpeg",
                            convert_options: { } #or whatever options you want
                          original_watermarked: {
                            processors: [:watermark],
                            watermark_path: "#{Rails.root}/app/assets/images/watermark.jpeg",
                            convert_options: { } #or whatever options you want
                          thumb: "100x100>",
    validates_attachment_content_type :picture_file, content_type: /\Aimage\/.*\Z/

Posted in Simple Form - Make label appear after input

I think that makes sense and a good approach - to mix and match! It worked for me in this case!


Posted in Simple Form - Make label appear after input

I have a simple form tag as given below:

= f.input :email, required: true, input_html: {class: 'md-input'}, wrapper_html: {class: 'md-form-group float-lable'}
and it generates the below HTML

* Email

How can I adjust the Simple Form tag such that the label element appears after the input element?

I've tried inline_label but that didn't seem to work as it was not intended for this purpose anyways

Posted in Storing Product Properties

I'm creating a jewellery product catalogue application and I need to store properties for each product such as material, finishes, product type etc.

I've concluded that there needs to be a model for each property, mainly because things like material and finishes might have prices and weights and other things associated with them.

Which of the two options will be the most efficient way to store data and be scalable

Create a model PropertyMap that will map property types and IDs to a Product ID.
Create several other models such as ProductMaterial, ProductFinish etc that will made a property to a product
All the data needs to be searchable & filterable. The database will probably index around 10K products.

Open to other smarter ways to store this data as well!

Posted in Backend and Frontend co-operation

In our rails applications, I generally work on the backend (models and controllers) while another developer focuses on the (Views + JS magic).

Generally he gets all the fields available from a model by looking at the schema.rb file, methods in the models or by asking me specifically for something.

Is there something more structured that we can use to co-operate?

Posted in Orders and Order Items

Exactly what I was looking for! Thank you so much Chris!

Posted in Orders and Order Items

I have 2 models, Orders and Order Items.

I want the user to be able to add any number of items to an order in the view. How can I structure a form so that I can iterate over the order items or is there a better way I could go about this?

Posted in Firefox rendering issues

The site - leanhire.co that I'm working on seems to render perfectly on Chrome but it seems to be a mess when I view the site via Firefox.

What do you think is missing and what is the best way to debug the issue?

Posted in Page Specific Javascript

We'll im looking at loading some elements via AJAX on page load on certain pages. I could check for the existence of certain elements and start making the AJAX calls but I'm guess there are simpler ways.

And I'm thinking that keeping the JS and the Rails code as separate as possible is generally a good idea.

Posted in Page Specific Javascript

I just came across this article that talks about a gem that allows you to implement cleanly space specific javascript.


However, it was written in Feb 2014, does anyone know if there is now a better way to do this?

Posted in rubber:passenger:add_to_pool takes forever

Nothing really :/

I changed the template to use nginx and unicorn. The app deployed perfectly then.

Ah well..

Posted in rubber:passenger:add_to_pool takes forever

I'm using Rubber 3.1.0 with Capistrano 2.15.5

When I try to deploy my app(default rails-devise-pundit) to production on EC2, it goes on perfectly till

command finished in 2849ms
triggering after callbacks for `rubber:apache:start'

  • 2015-06-12 20:43:29 executing `rubber:passenger:add_to_pool' ** Waiting for passenger to startup
  • executing "sudo -p 'sudo password: ' bash -l -c 'while ! curl -s -f http://localhost:$CAPISTRANO:VAR$/ &> /dev/null; do echo .; done'" servers: ["eye.circularsociety.com"] [eye.circularsociety.com] executing command ** [out :: eye.circularsociety.com] . ** [out :: eye.circularsociety.com] ** [out :: eye.circularsociety.com] . ** [out :: eye.circularsociety.com] ** [out :: eye.circularsociety.com] . What am I doing wrong? When I run cap rubber:tail_logs, I only see information related migration which I assume means that there's nothing wrong with the app?

Posted in Storing Constant Date in Rails

What is the best way to store a set of constants like country names, currencies, city lists in a rails app?

I was thinking of having a model named Constants that stores all this data and another model ConstantMaps that is polymorphic that maps the constants to the various other models

Is this a right approach?

logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.