ActiveRecord 4 how to user :order and :include
-
20-12-2019 - |
Question
I've just upgraded to Ruby 2.0 which by default will load ActiveRecord 4 for a Padrino app. This is fine, I'd like to take advantage of the Ruby 2.0 and AR 4 improvements. However, I'm having trouble rewriting some of the relations that worked before.
For example, this is no longer valid:
has_many :dvd_credits, :order => 'position', :include => [:dvd_actor, :dvd_role]
It gives a deprecated warning, but the example it shows is useless: has_many :spam_comments, -> { where spam: true }, class_name: 'Comment'
Looking around I was able to find that this works by omitting the :include
parameter:
has_many :dvd_credits, -> { order :position }
If I add it like so:
has_many :dvd_credits, -> { order :position, include: [:dvd_actor, :dvd_role] }
I get this error when I call that relation:
ArgumentError: Direction should be :asc or :desc
I'm still coming to grips with the changes to AR 4 but would really appreciate some help on this.
Thanks.
PS I did find this in the AR 4 page:
There's no need to use includes for immediate associations - that is, if you have Order belongs_to :customer, then the customer is eager-loaded automatically when it's needed.
Which I take it to mean that I can safely ignore the include:
parameter?
But this relationship is a bit complex, it goes like this:
class Dvd < ActiveRecord::Base
has_many :dvd_credits, -> { order :position }
has_many :dvd_actors, :through => :dvd_credits
has_many :dvd_roles, :through => :dvd_credits
class DvdCredit < ActiveRecord::Base
belongs_to :dvd_actor, :inverse_of => :dvd_credits
belongs_to :dvd_role, :inverse_of => :dvd_credits
belongs_to :dvd, :inverse_of => :dvd_credits
class DvdActor < ActiveRecord::Base
has_many :dvd_credits, :inverse_of => :dvd_actors
has_many :dvds, :through => :dvd_credits
But seems to fulfill the belongs_to
condition.
Solution
Yea, you can just ignore the :include
part.