简体   繁体   English

不可能的Rails语法:命令has_many具有多态关联

[英]Impossible Rails Syntax: Order has_many with polymorphic association

Statically-typed, compile-time-checked programmer brain, here, struggling with a rails function call. 静态类型的,经过编译时检查的程序员大脑在这里与Rails函数调用作斗争。

In a model when we specify has_many , we can specify the sort order like this has_many :requirements, -> { order(created_at: :asc) }, :dependent => :destroy . 在模型中,当我们指定has_many ,我们可以指定排序顺序,例如has_many :requirements, -> { order(created_at: :asc) }, :dependent => :destroy

But when we have a polymorphic association such as this has_many :text_fields, as: :describable, :dependent => :destroy how can we add the sorting lambda? 但是,当我们具有诸如has_many :text_fields, as: :describable, :dependent => :destroy这样的多态关联时,例如has_many :text_fields, as: :describable, :dependent => :destroy ,我们如何添加排序lambda?

I have tried every possible permutation of syntax except, apparently, the correct one. 我尝试了所有可能的语法排列方式,但显然是正确的。

You have clarified that it is the child records (text_fields) that you want ordered. 您已澄清,它是要排序的子记录(text_fields)。 You could use a default_scope , like so: 您可以使用default_scope ,如下所示:

class ParentModel < ApplicationRecord
  has_many :text_fields, as: :describable, :dependent => :destroy
end

class TextField < ApplicationRecord
  default_scope { order(created_at: :asc) }
end

But think hard before doing so because default_scope is evil . 但是在这样做之前要三思而后行 ,因为default_scope是邪恶的 Among other things, you can't override an order that is defined in a default_scope. 除其他事项外,您无法覆盖default_scope中定义的order I am not familiar with requirements , but you may not be able to override the order defined within requirements either. 我不熟悉requirements ,但是您也可能无法覆盖requirements中定义的顺序。

I think you are much better served creating a scope like so: 我认为创建这样的范围会更好:

class ParentModel < ApplicationRecord
  has_many :text_fields, as: :describable, :dependent => :destroy
end

class TextField < ApplicationRecord
  scope :default_order, -> { order(created_at: :asc) }
end

Then call it explicitly when you want your records ordered that way: 当您希望以这种方式对记录进行排序时,请显式调用它:

TextField.all.default_order

or 要么

parent_record.text_fields.default_order

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM