Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
rails 4.1 cannot eager load polymorphic associations
gem 'activerecord', '4.1.0.rc1'
# gem 'activerecord', '4.0.2'
require 'active_record'
require 'minitest/autorun'
require 'logger'
puts ActiveRecord::VERSION::STRING
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Schema.define do
create_table :feed_entries, :force => true do |t|
t.integer :feedable_id
t.string :feedable_type
end
create_table :trainings, :force => true do |t|
t.integer :user_id
t.boolean :featured, default: false, null: false
end
create_table :users, :force => true do |t|
end
end
class FeedEntry < ActiveRecord::Base
belongs_to :feedable, polymorphic: true
def self.with_featured_training
joins("LEFT JOIN trainings ON feed_entries.feedable_type = 'Training' AND feed_entries.feedable_id = trainings.id")
.where(trainings: {featured: true})
end
end
class Training < ActiveRecord::Base
belongs_to :user
has_many :feed_entries, as: :feedable
end
class User < ActiveRecord::Base
end
class TestMe < MiniTest::Unit::TestCase
def test_polymorphic_eagerload
user_1 = User.create!
user_2 = User.create!
training_1 = Training.create!(user: user_1, featured: true)
training_2 = Training.create!(user: user_2, featured: true)
FeedEntry.create!(feedable: training_1)
FeedEntry.create!(feedable: training_2)
scope = FeedEntry.with_featured_training.includes(feedable: [:user])
scope.each { |fe| fe.feedable.user }
end
end
@morgoth

This comment has been minimized.

Show comment
Hide comment
@morgoth

morgoth Feb 24, 2014

This throws error in rails 4.1, but it was working fine in 4.0.x

Owner

morgoth commented Feb 24, 2014

This throws error in rails 4.1, but it was working fine in 4.0.x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment