oystersauce8
oystersauce8

Reputation: 551

rails 1 to 4 upgrading the :include keyword

I have a whole bunch of Rails 1 code that uses this syntax in models:

...
has_many :widgets, :class_name => 'WidgetAssertion', 
                   :include => [ :activity, :priority_assertion_type ]
...

Rails 4 throws an exception:

(ArgumentError in WhateverController#index) 
(Unknown key: :include. Valid keys are: :class_name, :class, :foreign_key,
:validate, :autosave, :table_name, :before_add, :after_add, :before_remove, 
:after_remove, :extend, :primary_key, :dependent, :as, :through, :source, 
:source_type, :inverse_of, :counter_cache, :join_table, :foreign_type)

How can I port this to Rails 4?

Upvotes: 2

Views: 554

Answers (1)

Chris Peters
Chris Peters

Reputation: 18090

The 2nd argument of has_many is scope:

You can pass a second argument scope as a callable (i.e. proc or lambda) to retrieve a specific set of records or customize the generated query when you access the associated collection.

So, in your example, you could do this:

has_many :widgets, -> { includes(:activity, :priority_assertion_type) },
         class_name: 'WidgetAssertion'

Upvotes: 3

Related Questions