1

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!

Andrew Algard
  • 105
  • 1
  • 12

1 Answers1

2

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.)

Ilya Konyukhov
  • 2,666
  • 1
  • 12
  • 21
  • thanks for the response! hmm yeah I was worried this might be the solution. Really don't want to clutter up all the models with these conditions everywhere. Is there a way to write a single scope on a relationship that is valid in Rails 3 and Rails 5? – Andrew Algard Oct 01 '18 at 19:19
  • Well, simple cases such as ```has_many :companies_projects, class_name: 'CompaniesProject'``` can be left unchanged. What about ```arel```-related query modifiers, in Rails >= 4 they are accepted only as a callable ```scope```, not as a ```options``` hash of ```has_many```. I was trying to solve this dilemma a year ago too but eventually stayed with the solution above. – Ilya Konyukhov Oct 01 '18 at 19:31
  • ah well hopefully this upgrade won't take _too_ long... thanks for the help – Andrew Algard Oct 01 '18 at 20:20