How do I destroy a ActiveModel instance with dependant destroy children that have a default ordering?

佐手、 提交于 2019-12-25 09:21:59

问题


In Rails 4.0 I have 2 ActiveRecord classes:

class Sequence < ActiveRecord::Base

    has_many :steps, dependent: :destroy

end

and

class Steps < ActiveRecord::Base

    belongs_to :sequence

    default_scope -> { order('order ASC') }

end

When I call mySequence.destroy I get this error:

PG::SyntaxError: ERROR: syntax error at or near "order" LINE 1: ...steps" WHERE "steps"."sequence_id" = $1 ORDER BY order ASC ^ : SELECT "steps".* FROM "steps" WHERE "steps"."sequence_id" = $1 ORDER BY order ASC

When I remove the default scope, the error is gone, but I obviously have to order the steps in my sequence in my code. I did try to define the association like this, and leaving out the default_scope statement:

class Sequence < ActiveRecord::Base

    has_many :steps, dependent: :destroy, order: 'order ASC'

end

but it threw the same error.

Does anyone else have this issue? Is this a bug in Rails? I imagine the ordering is not needed in the destroy sql statement on the children.


回答1:


I posted this issue on the rails gitHub issue page as well. gitHub user tanraya suggested the following elegant solution.

default_scope -> { order order: :asc }

Thanks from over here, tanraya, and kudos!



来源:https://stackoverflow.com/questions/20337750/how-do-i-destroy-a-activemodel-instance-with-dependant-destroy-children-that-hav

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!