Today I Learned

TIL, 2017-06-20

Singapore Ruby Group Meetup

To ORM or not to ORM - Mykola Kyryk

  • Web dev is mostly about CRUDs.
  • ORM/AR: AR wraps a row in a database table or view, encapsulates database access, and adds domain logic on that data.
  • AR: If you need to get values from multiple tables, what do you do?
  • PocketMath workflow: customer creates ad campaign, platform receives traffic, then we check if the click can be linked to us.
  • API endpont: See money spent and clicks per campaign.
{
  campaign_name => campaigns table
  total_budget => campaigns table
  spend => money spent, from stats table
  clicks => clicks, from stats table
}
  • New requirement, if you need to measure the campaign stats for a user, since campaign belongs_to customer.
  • You do the map thing, but you will run into the N+1 query.
  • You can do the join thing customer.campaigns.join(:stats), but you don’t select stats and customer table by default.
  • You can do the custom select, but it returns more rows.
  • You can do the custom select with join, using an aggregate as and group.
  • Moving the query to the scope: you either do the custom SQL as a scope, or you use Arel in the scope.
  • Result: You are able to select values from 2 tables, db does the heavy lifting, you can customize AR with SQL.
  • Problem: AR is expensive. The solution is to do the pluck method, the problem is that you can’t call methods defined on an AR class. You need to do the as spend.
  • So that solves the thing, but new problem. How do you do the same thing. You can create an SQL view. Um technically you can actually do an inherits from AR::Base, but you can’t do inserts. You can only do wheres.

Summary

  • Prefer pure SQL to Arel, because you never change databases anyway (and if you do change, db-specific things like groups will not work.
  • ORM for third party code, since it returns AR::Relation. You can use things like kaminari, paper_trail
  • SQL database view comes with db:schema:load.

Releasing your First Gem - Peter

  • Need to do mail migrations, previously this was a shell script.
  • Swiss Army Knife for SMTP

Peter’s Rules

  • Google it.
  • You will write code so ugly, not even a mother can love it.
  • Nobody will read it anyway.

Confess Your MongoDB Opinions - Emily Stolfo

  • Postgres has JSON support so why Mongo? You can index inside the keys, but you can’t aggregate inside the keys.
  • All data is relational, so what data do you gain?
  • MongoDB good points: aggregation?
  • Rails people think in models and database tables.
  • Aggregating thing is done in C++, faster than map reduce JS.

This project is maintained by daryllxd