Skip to content

Instantly share code, notes, and snippets.

@pjurczynski
Created July 14, 2016 07:24
Show Gist options
  • Save pjurczynski/af704de9effcf407ddbc2c49ff4963c7 to your computer and use it in GitHub Desktop.
Save pjurczynski/af704de9effcf407ddbc2c49ff4963c7 to your computer and use it in GitHub Desktop.
Arel Table

Arel Table

The problem: You want some advanced function from sql, but active record won't help

Example: SELECT * FROM users WHERE name LIKE '%hacker%'

Active Record: User.where("name LIKE '%?%'", 'hacker')

Why it's bad?

User.joins(:pet).where("name LIKE ?", '%hacker%')

Mysql2::Error: Column 'name' in where clause is ambiguous

bad fix: User.joins(:pet).where("users.name LIKE ?", '%hacker%') rails appends silly AS names like "t0_r1". You can't deal with it with fixed strings

good fix:

user_name_match_hacker_query = User.arel_table['name'].matches('%hacker%')
User.joins(:pet).where(user_name_match_hacker_query)

SELECT * FROM users as t0_r1 JOIN pets AS t1_r1 ON t0_r1.pet_id = t1_r1.id WHERE t0_r1.name LIKE '%hacker%'

Sky is the limit:

column = User.arel_table['updated_at']
Arel::Nodes::NamedFunction.new('CAST', [column.as('DATE')])

CAST(users.updated_at AS DATE)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment