Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

has_many :through association ordering not honored #16

Open
deep-spaced opened this issue Mar 8, 2016 · 0 comments
Open

has_many :through association ordering not honored #16

deep-spaced opened this issue Mar 8, 2016 · 0 comments

Comments

@deep-spaced
Copy link

Hello! I'm running into some issues when using a has_many :through association and I was wondering if you could point me in the right direction. I've got a model association like this:

class Page < ActiveRecord::Base
  has_many :block_associations, as: :blockable, dependent: :destroy
  has_many :blocks, through: :block_associations
end

class Block < ActiveRecord::Base
  belongs_to :block_type
  has_many :block_associations
end

class BlockAssociation < ActiveRecord::Base
  belongs_to :block
  belongs_to :blockable, polymorphic: true

  default_scope { order(sort_order: :asc) }
end

My drop setup for the Page model is also fairly straightforward:

class PageDrop < Liquid::Rails::Drop
  has_many :blocks
end

However, when I reference page.blocks in the template, the ordering is not honoring the order set by the default_scope in the BlockAssociation model. Looking through the logs, I'm seeing these queries:

BlockAssociation Load (1.2ms)  SELECT "block_associations".* FROM "block_associations" WHERE "block_associations"."blockable_type" = 'Page' AND "block_associations"."blockable_id" IN (2)  ORDER BY "block_associations"."sort_order" ASC
Block Load (0.5ms)  SELECT "blocks".* FROM "blocks" WHERE "blocks"."id" IN (377, 305, 6765, 278, 604)

It looks like the block IDs are being retrieved and then a single query to get the blocks is done, but that leads to the blocks being sorted by ID, not by the sort_order field set on the BlockAssociation join table.

The typical query as generated by ActiveRecord is as follows:

SELECT "blocks".* FROM "blocks" INNER JOIN "block_associations" ON "blocks"."id" = "block_associations"."block_id" WHERE "block_associations"."blockable_id" = $1 AND "block_associations"."blockable_type" = $2  ORDER BY "block_associations"."sort_order" ASC  [["blockable_id", 2], ["blockable_type", "Page"]]

Unfortunately, all I've been able to figure out so far is to define a method to return the blocks manually:

def blocks
  @object.blocks.order('block_associations.sort_order ASC')
end

That, of course, generates another SQL query. Any thoughts on how I could fix this, or maybe point me towards the code? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant