mercredi 17 août 2016

Converting belongs_to with includes from Rails 3 to Rails 4

I'm having trouble converting a belongs_to relationship with an includes from the Rails 3 format to Rails 4.

# Rails 3, this works fine.
class Mobileownerdisclosure < ActiveRecord::Base
  belongs_to :mobileuser, foreign_key: 'mobileowner_id', conditions: "mobileownerdisclosures.mobileowner_type = 'Mobileuser'", include: :mobileownerdisclosures
end

# Rails 4 format that I can not get to work...
class Mobileownerdisclosure < ActiveRecord::Base
  belongs_to :mobileuser, -> { where("mobileownerdisclosures.mobileowner_type = 'Mobileuser'").includes(:mobileownerdisclosures) }, foreign_key: 'mobileowner_id'
end

The .includes(:mobileownerdisclosures) just doesn't seem to be considered at all. However, if I change this from an includes to a joins, it works fine.

# Rails 4 format with joins instead of includes.
class Mobileownerdisclosure < ActiveRecord::Base
  belongs_to :mobileuser, -> { where("mobileownerdisclosures.mobileowner_type = 'Mobileuser'").joins(:mobileownerdisclosures) }, foreign_key: 'mobileowner_id'
end

But since I am converting a very large project from Rails 3 to Rails 4, I'd rather keep it includes like the original intent, just to be sure the original coder didn't need it this way.

Why is the includes not being considered? Is there a different way to use includes other than what I am doing there?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire