1

My Miniature model has the following association:

class Miniature < ActiveRecord::Base
  has_many :minilines, dependent: :destroy
  has_many :lines, :through => :mini lines

This works fine but I wanted to have the Minilines sorted alphabetically by name so I added this:

class Miniline < ActiveRecord::Base
    default_scope { order('name ASC') }
    belongs_to :miniature
    belongs_to :line

I thought that was working fine but when you come to delete a Miniature you get an error:

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: name: SELECT "minilines".* FROM "minilines" WHERE "minilines"."miniature_id" = ? ORDER BY name ASC):
app/controllers/miniatures_controller.rb:205:in `destroy'

Removing the default_scope line allows you to delete the Miniature and has the correct behaviour.

It's not clear to me why the default_scope breaks this behaviour or how to rectify it.

My question appears to be duplicate of this but the ticked solution there doesn't solve it for me.

Community
  • 1
  • 1
Ossie
  • 1,103
  • 2
  • 13
  • 31
  • possible duplicate of [default\_scope breaks (update|delete|destroy)\_all in some cases](http://stackoverflow.com/questions/3944019/default-scope-breaks-updatedeletedestroy-all-in-some-cases) – Roman Kiselenko Jul 30 '14 at 10:20
  • Sort of. The difference is I'm not trying to delete_all or update_all so the answers on that Q don't seem to apply to mine. I can't see an answer there that looks like it will fix my problem. – Ossie Jul 30 '14 at 10:30
  • Quite strange. Are you sure there is `minilines.name` column? What does `Miniline.all` return in console? – Marek Lipka Jul 30 '14 at 10:31
  • Aha! No there isn't a mini legions.name column, it's the name column from the associated Line model. The sort works on the association but I guess it trips up the destroy somehow. – Ossie Jul 30 '14 at 10:35

1 Answers1

0

You should probably have:

default_scope { joins(:line).order('lines.name ASC') }
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • Yes! So whilst my slightly shorter default_scope code worked for the sorting it confused ActiveRecord when it came to deleting. Fair enough. This is a great solution and I didn't know you could be so precise with a joined model order. Great. – Ossie Jul 30 '14 at 10:42