Refactor SQL in Rails Way style