ActiveRecord::Associations::AliasStrategy

While working with rails I always find it confusing how aliases are created for tables:

  • it’s unpredictable - changes with where referencing the association
  • it’s counter intuitive - alias_candidate"#{plural_name}_#{name}"
  • it does not match the join(*relations), so I need to check to_sql to know what name to use

I’ve implemented ActiveRecord::Associations::AliasStrategy which preserves the existing behavior as Default and implemented Consistent strategy so people can change the strategy on new applications, and use names consistent with their join mentioned relations in where clauses, but to not break existing huge code bases already having hardcocded a lot of the custom names in code.

While I work on adding tests and documentation I thought I would share my working implementation for review and guidance on direction for it:

1 Like

I’ve been wanting better alias handling when doing joins on the same table in the same query and then needing to reference one of those aliases elsewhere in the query. You change an association name, and then you need to verify which alias rails decided to use in order to update your query.

I’d like to see some tests with your new strategy to get a better idea of how things are working.