ActiveRecord: Change foreign key to a field other than the join table’s id

A good example for this implementation is when you have a table of retail stores that references a table containing US states. By convention, when adding a state reference to the stores table, a state_id column is created:

class AddStateToStores < ActiveRecord::Migration
  def change
    add_reference :states, :store, index: true, foreign_key: true

But say you want to see the human readable state code rather than its id when querying stores because joining two tables every time is too much work. You may want to change the foreign key from state_id to state_code.

Here is how it’s done step by step (referencing this SO answer):

– Add a state_code column to stores table and update the new state_code column during migration using a join statement:

class AddStateCodeToStores < ActiveRecord::Migration
  def up
    add_column   :stores, :state_code, :string
    query = "UPDATE stores AS A SET state_code = B.code FROM states AS B" +
            "WHERE A.state_id ="

  def down
    remove_column :stores, :state_code, :string

– Specify a different foreign key for states:

class Store << ActiveRecord::Base
  belongs_to     :state, foreign_key: 'state_code',
                         primary_key: 'state_code'

– Now you can safely drop the state_id column from the stores table.

Testing: Set up shoulda matchers + VCR cassettes

The more I progress into my career as a software engineer, the more I realize the importance of test coverage. I don’t do TDD but find a lot of value to a decent test coverage. When you push a feature branch to Github and your continuous integration tool (in my current case Semaphore) tells you that tests fail, it is much faster and reliable to fix your logic or your test right away, rather than encountering a bug later on.

I plan to do some posts on testing, beginning with how to set up shoulda matchers and VCR cassettes (with Rails and RSpec).

Shoulda matchers

Shoulda matchers is a gem by Thoughtbot that provides quick helper phrases to test common functionality of Rails. In the Bedrocket API, we use shoulda matchers mostly to to test model validations and associations, but the library also has some Action Controller matchers.

– Example:

# item.rb
class Item
  validates       :name, presence: true
  belongs_to   :category

# item_spec.rb
describe Item do
  it { should validate_presence_of(:name) }
  it { should belong_to(:category) }

Installing shoulda-matchers

Personally I’ve ran into an error while installing gem shoulda-matchers:

Failure/Error: it { should validate_presence_of(:email) }
undefined method `validate_presence_of' for #RSpec::Core::ExampleGroup::Nested_1:0x105aa4938
# ./spec/models/user_spec.rb:4

I’ve searched and found out a way to avoid this error:
– Gemfile: Put shoulda matchers only in group test, with require: false param.

group :test do
  gem 'shoulda-matchers', '~> 2.8.0', :require => false
  gem 'fabrication'

– spec_helper: Require shoulda matchers

require 'rspec/rails'
require 'shoulda-matchers'


VCR Cassettes

VCR Cassettes records HTTP responses in yml files and “replay” them later for faster testing. It needs to be used with a HTTP stubbing tool, in this case webmock.

– Setting up:
+ Require the gems in group test:

group :test do
  gem 'webmock'
  gem 'vcr'

+ Configure VCR in spec/spec_helper.rb:

VCR.configure do |c|
  c.cassette_library_dir = 'spec/vcr'
  c.hook_into :webmock

cassette_library_dir is the folder where the responses are saved.

+ The controller spec is like so:

describe 'AnalyticsController', vcr: { match_requests_on: [ :host ] } do
  describe 'write analytics' do
    # contexts and expectations

– How it works:
+ match_requests_on parameter tells your spec when to use VCR pre-recorded responses for the result of the test. In this case, I simply want to match all requests of a certain host. But VCR also allow you to match requests by HTTP method, specific URI, URI path, URI query string, request body and headers (request matching doc).

+ Record mode: The default mode is record: once. This means VCR records the HTTP response when there are no yml files present for that request. When the spec is run subsequently, VCR will use the recorded response instead of making the request again.

+ See all record modes. To change record mode, simply add it as an argument:

describe 'AnalyticsController', vcr: { match_requests_on: [ :host ], record: new_episodes } do

+ When using the record once mode, simply delete the yml files to re-record responses. You should remember to re-record when code is changed to make sure that the spec still works correctly.

Trendy, minimal active leggings

You know what I love? Leggings. I retired most of my low-rise jeans two years ago. When high-waist jeans became trendy, I started stocking up on black leggings. Being lucky to work in offices with casual dress codes, I can wear leggings instead of pants. They look just as good with suede high-heeled booties and lace-up boots as they do high-top sneakers. Win win!

Recently I also became more active, doing pole, aerial silk and yoga. The last two require long, form-fitting pants, so I’d been obsessed with hunting for the perfect pair of trendy leggings that fit with my personal minimal style. What I truly hate most about shopping for yoga pants are all the crazy prints, tie-dye colors, and super busy patterns. Why?!?!? Thankfully I was able to narrow down to these two candidates:


Onzie Mesh Leggings

1. Onzie track mesh leggings

Mesh cut-out leggings suddenly became really hot this season. I see them a lot on the street and am inexplicably drawn to them. A few stores carry this style, but the cutouts aren’t always tasteful. This Onzie pair has a large sheer area but is also very streamline. Most importantly they look flattering.

2. Outdoor Voices colorblock leggings

One day I saw a yoga teacher at Sky Ting Yoga (Lower East Side) wear these amazing light grey colorblock pants, and immediately went online to search for them after class! I found a very similar pair online at Outdoor Voices, which turns out to be a boutique store in SoHo.

The funny thing is that I discovered later on that Outdoor Voices merchandise is sold at the studio. So I must’ve found the exact pair the instructor was wearing. This just goes to show that minimal is not always easy. It’s really hard to find a store that offers a design similar to this right now. I’m waiting for the pants to get back in stock so I can splurge on them!


Disappointing How to Get Away with Murder season 2 finale

htgawmWords cannot describe how sensational season 1 was to me. It was sexy, refreshing and just the right amount of shocking, episode after episode. But everyone knows, what goes up must come down. In season 2, the show started showing signs of losing momentum.

In order to get away with murder, there has got to be even more murders. Even though we know they can’t get away with it, the show has to go on with a more and more complicated web of victims, killers, lies and deceit.

I think the worst part about season 2 is that it doesn’t wrap up the main murder case like season 1 did. We still don’t know how exactly the Hapstall parents died, as we found out who killed Lila, even though the latest evidence pointed to a shady liaison between Catherine and Philip. Are the producers afraid they would run out of ideas for the next season and thus try to keep this plot under wrap?

Below are the high and low moments from season 2:

– Frank and Laurel getting together – steamy!
– Bonnie’s abusive past, what she’s capable of doing and her bonding with Asher over tragedy.
– Nate’s wife’s death and his coming back to Analise.
– Catherine’s and Caleb’s incestuous kiss.

Lows (and things that just don’t make sense):
– Wes being pushed to sidelines this season. The best part was the season premiere, where it was ominously implied that he shot Analise. Thankfully we’re going to find out more about him next season, as the very final flashback of the season hinted at the circumstance of his mother’s death.

– Asher’s involvement in the Trotter Lake incident. Being a covered up case that was used against him and his father by DA Sinclair, it turned out to be serious but still unclear whether Asher took part in raping the girl at all.

– Caleb’s romantic interest. Apparently he and Catherine have been in love growing up, yet suddenly started hooking up and having feelings for Michaela? They’re gorgeous together but the setup doesn’t make a lot of sense.

– The involvement Philip Jessup. The character was brought in mid-season and is a cliched socially awkward cyber geek type. It’s a typical red herring to make you think the weird guy did it, but his character and back story (if at all) has been poorly exploited.

– Blaming Sinclair’s murder and Analise’s gun shot on Catherine. The motive behind killing Sinclair is super dubious and the injury doesn’t even match her cause of death. Furthermore, Frank drugged and dropped the girl unconscious in the middle of the woods with no blood or DNA on her from the supposed victims. I just don’t see how this is going to work.

So what’s going to happen next season? I hope the pace picks up again, truly.

How Fifty Shades of Grey could have been a less boring movie

fifty-shades1Here is my review for the movie everyone is buzzing about this Valentine’s Day. I read the three books a while ago. The movie was not a total waste of money but I could think of several ways it could have been less boring:

– It could have gone down a darker route, like The girl with a dragon tattoo or Gone girl, instead of the romantic route like Twilight. In fact, Jamie Dornan’s millionaire playboy with the a fancy penthouse and private helicopter is enticing but is nowhere near magnetic as brooding vampire Edward Cullen.

– Anastasia mumbled her way throughout the movie. They should have at least given her some narration like Bella, so she could express some of her virginal thoughts and desires in ways other than flashing her nipples and biting her lips.

– I was not too impressed with the cast from the beginning but Dakota Johnson’s body turned out to not be a bad choice. However, call me brainwash by Photoshop and Hollywood movies, Jamie Dornan’s physique is not that impressive. He’s not supposed to be too buff but, as this is a movie about fantasies, I expect to be wowed with a body like Chris Hemsworth’s in Thor or Channing Tatum’s in Magic Mike.

– Again, they could really amp up the dark side of Christian or tease for the next movies by giving some flashbacks of his prostitute mother or of him being whipped by Mrs Robinson. There’s no evidence of this character’s fucked up psychology other than the fact he has a playroom filled with some scary looking instruments. Boring! Even the piano playing scene has no emotion or depth to it.

– Anastasia’s mother is unusually attractive, but the young cast is weird looking: from roommate Kate to Christian’s brother with the creepy Elliot blonde beard. Mia appears for (literally) two seconds with a severe 1920s black bob because she ‘lives in Paris’, which is weird and not as cute as Alice’s pixie cut. Personally I found Christian’s chauffeur Taylor more attractive. His involvement is almost entirely cut out in the movie, even though they could have used the relationship to play up Christian’s controlling personality.

Basically, 50 shades of grey is a cliched romance flick with nudity, not a sexy movie about the BDSM lifestyle, which is a shame. I’d say the only winner from this franchise is The Weeknd with this seductive soundtrack:

Safely plug a Rails app into an existing database

rails deploymentTraditionally there’re a few ways to set up your Rails database using rake tasks:
rake db:create db:migrate
Create a new database and run migrations
rake db:schema:load
Drop database if it exists and create tables according to your schema.
rake db:setup
Will run both rake db:schema:load and rake db:seed

db:schema:load is problematic. It is suggested in Rails schema.rb file that this is an efficient way (compared to db:migrate) to set up your database. However, it assumes that a) you have a database dedicated to the Rails app, b) have no existing data. But what if you want to create tables for your Rails app in an existing database with other important data?

Here’s a guide I’ve come up with on how to forgo migrations and integrate your Rails app into an existing database:

 1. Create tables in your production database
Feel free to namespace them like this: myproject_users instead of just users.

2. Edit database.yml
Specify the name of your database and the user/password that has access to it under the corresponding environment setting (development or production).

3. Void migration files
Under db/migrate, either comment out the files’ content or change their extension to .txt.

4. Schema dump
db/schema.rb is auto generated by running migrations. Since you don’t plan to run them, rake db:schema:dump will update schema.rb and allow it to be used with ActiveRecord.

5. Set custom table names for models
If the name of the tables are different from ActiveRecord convention (e.g.: you namespace the tables), add this to the model self.table_name = "[custom table name]". This will help Rails find the tables and avoid error.

Hope that was somewhat helpful. I’m also looking into deploying with Capistrano and submitting a pull request that would give a warning when you try to run rake db:schema:load.

Thoughts on Manhattan Love Story getting axed

A fragile fate

I checked weekly for new episodes of Manhattan Love Story (MLS) on Hulu for a month and didn’t see anything. Suddenly this weekend, 7 new episodes appeared out of thin air. So naturally I binged on them.

This morning, I realized that the MLS was cancelled in late October and episode 5 never even made it to the air (!) Apparently the last episode on air hit an all-series low of 2.6 million viewers, and that was the last drop. It’s very unfortunate because the third episode, which introduced Dana’s gay British boss, was truly hilarious.

Even though MLS received poor critical ratings, the fact that the network decided to drop it completely from air based on Nielsen ratings strikes me as strange. Personally I don’t watch any show when it airs (and I watch a fair amount). Do other forms of viewership (online/streaming) hold no weight? What’s worse is that ABC attempted to replace MLS with a back-to-back episode of Selfie, which is even more boring and less funny in my opinion.

On the plot and characters
I was rather excited when I saw MLS trailer in the summer. How could I not? I’m a sucker for rom coms, especially those that involving the superficial, flaky, fascinatingly cut-throat NYC dating scene.

MLS2Here’s how the show is realistic:
– The awkward run-in between Dana and Peter when he’s on a date with a regular hottie.
– Dana feigns dating ‘other’ people and not showing too much enthusiasm at Peter’s invitations to hang out.
– Dana and Peter both being invited to a party to which he had previously invited another date as a plus one.
– Amy’s huge SoHo loft in simply  is explained by the fact that she’s born rich and doesn’t have to work.

Why it fell short of living up to its promise:
– The two main characters are too stereotypical and have no depth. Dana, a small-town girl who gets a ‘dream job’ at a publishing company, is very flighty, unrealistically clumsy and doesn’t have much going in her work place besides being shunned by bitter old-timers, making copies and fraternizing with her dashingly handsome boss slash gay BFF. In the trailer scene, she is simply heard lusting after designer purses even though her character is not portrayed as being that into or involved with fashion.

MLS3– Peter is none other than ‘that guy’ – the bro, the douche bag and womanizer. The longest relationship he’s ever had is 10 months long despite being well into his twenties. He is that guy who is only nice looking (compared to other TV’s leading males!) but is ‘that hot’ in the dating pool just because he has somewhat of a sense of style and social skills around women.
– Such cliched, overwrought dating ploys and mishaps, e.g.:
+ Struggling to find date to an event to impress the other person you’re seeing
+ Not being able to consumate their relationship due to food poisoning
+ Freaking out about him proposing although you’ve obviously only dated for 3 months (monogamously 2 at most)

Entertaining points
– Some of the supporting cast are way more interesting than what goes on in Dana’s and Peter’s heads. Amy is pretty funny – she’s the essential smart, put-together, overly controlling know-it-all in every show. On Peter’s side, his step sister Chloe is the most down-to-earth, logical voice of the whole family. They provide some rationality and relief to the ridiculous, non-sense mess made by our leads.

– Of course, the wardrobe of the show is amazing. I plan to dedicate a separate post to it.