Upgrade Rails 3 to 5, scope block syntax

146 views Asked by At

I'm upgrading an app from Rails 3.2 to 5.2, I need to have both versions running at the same time and have run into an issue with the scope block syntax.

I've got this relationship on a Project model

has_many   :companies_projects, include: :company_type, order: 'company_types.order_id'

which gives this error in Rails 5

Unknown key: :include. Valid keys are: :class_name, :anonymous_class, :foreign_key etc...

i can fix this by changing the syntax to this:

has_many   :companies_projects, ->{ includes( :company_type ).order('company_types.order_id') }

but then in the rails 3 app it causes this error:

wrong number of arguments (1 for 0)

is there a happy medium where this scope block will work in both rails 3 and 5? any help would be appriciated, thanks!

1

There are 1 answers

3
Ilya Konyukhov On BEST ANSWER

Great question!

You can solve this puzzle by replacing your relation with this conditional expression:

if Gem::Requirement.new('>= 4.0.0').satisfied_by?(Gem.loaded_specs['activerecord'].version)
  has_many :companies_projects, ->{ includes(:company_type).order('company_types.order_id') }
else
  has_many :companies_projects, include: :company_type, order: 'company_types.order_id'
end

It checks which version of the activerecord gem is loaded, and creates relationship using suitable syntax.

(I might be wrong but as I remember new syntax of has_many was introduced in the version 4.0.0.)