Search code examples
mysqlruby-on-railsrubyransacksqueel

Can't access SQL column aliases in Rails 4.1


After upgrading my rails app from 3.2 to 4.1.13 one of my queries doesn't seem to be making aliased columns available to ActiveRecord (I think). If I run .to_sql and query using that SQL I can clearly see the aliased columns are being returned but when I try to access them like I used to I get undefined method errors.

I'm not sure how to troubleshoot this.

The query is built from a Ransack search and some Squeel joins.

search_result = search.result.in_current_club_type.
  joins{role.outer}.joins{contact.outer}.for_current_or_last_year.with_fellowship.
  select(<<-SQL
    people.id, people.last_name, people.first_name, people.parent_only, clubs.name AS club_name,
    roles.name AS role_name, tlt, master_guide, pla, grade, people.type, people.email,
    contacts.primary_phone AS phone
  SQL
  )

The aliases I'm needing to access are role_name, club_name, and phone. I've placed a binding.pry right after that and attempt search_result.first.role_name and the returned error is

NoMethodError: undefined method `role_name' for #<Member:0x007fa8bcf121d0>

I could turn those into instance methods, but I'd like to be able to continue with the existing way of doing things if possible.

Thank you for your guidance.


Solution

  • Ok, I don't know exactly why but it seems that search was being built from a scope that needed to be rewritten using Squeel syntax. Then things joined properly and I could call the aliased columns.

    Old Scope

    scope :unapproved, -> { joins(approvals).where('approvals.approved IS NULL OR approvals.approved = ?', false) }
    

    New Scope

    scope :unapproved, -> { joins{approvals}.where{(approvals.approved == nil) | (approvals.approved == false)} }