mardi 19 juillet 2016

Rails, Query polymorphic association

I'm trying to querying on polymorphic associations in Rail, and come across with this problem. I have a few models, User, MorningVisit, AfternoonVisit, NightVisit, and Result

class User < ActiveRecord::Base
    attr_accessible :name
    has_one :morning_visit
    has_one :afternoon_visit
    has_one :night_visit
end

class MorningVisit < ActiveRecord::Base
    belongs_to :user
    has_many :results, as: :visitable
end

class AfternoonVisit < ActiveRecord::Base
    belongs_to :user
    has_many :results, as: :visitable
end

class NightVisit < ActiveRecord::Base
    belongs_to :user
    has_many :results, as: :visitable
end

class Result < ActiveRecord::Base
    belongs_to :visitable, polymorphic: true
end

Everything stores perfectly, but now I need to do some search and querying on User using filterrific.

If I do

includes(:visitable => :user).order("user.name")

I get

Can not eagerly load the polymorphic association :visitable

So I tried to manually joined MorningVisit with

.joins( "JOIN morning_visits ON lab_results.visitable_id = morning_visit.id AND lab_results.visitable_type = 'MorningVisit'")
.joins( "INNER JOIN `users` ON `morning_visits`.`user_id` = `users`.`id` ")

And order("user.name") works.

But if I added

.joins( "JOIN afternoon_visits ON lab_results.visitable_id = afternoon_visits.id AND lab_results.visitable_type = 'AfternoonVisit'")

It returns nothing. And if I tried outer join, it keep telling me my SQL syntax was wrong.

Does anyone have a solution for this?

Aucun commentaire:

Enregistrer un commentaire