微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将类方法转换为两个模型之间的关系?

如何解决如何将类方法转换为两个模型之间的关系?

我有 BasePlan has_many 的模型 Plan。我们在 BasePlan 中使用类方法按字母顺序对关联的 Plan 进行排序,我需要将其重构为两个模型之间的关联。

BasePlan 类:

has_many :plans,-> { extending BuildWithAccount },inverse_of: :base_plan,dependent: :destroy

Plan 类:

belongs_to  :base_plan

BasePlan 按字母顺序排列计划的类方法

  def order_plans_alphabetically
    plans.order(code: :asc)
  end

我在 BasePlan 中创建了一个新关联,如下所示:

has_many :alphabetically_ordered_plans,-> { order_plans_alphabetically },class_name: "Plan"

结果:

NameError: undefined local variable or method `order_plans_alphabetically' for #<Plan::ActiveRecord_Relation:0x00005593e3876460>

我还尝试将 class 方法包含在现有关联的 lambda 中,导致 100 多个测试失败,因此我认为这也不是可行的方法

将类方法重构为两个模型之间的关系的有效方法是什么?

解决方法

has_many :alphabetically_ordered_plans,-> { order(code: :asc) # short for Plan.order(code: :asc) },class_name: "Plan"

评估 lambda 的上下文不是 BasePlan 类),而是您关联的类(Plan)。如果你真的想使用一个范围(基本上只是一个类方法),你需要把它放在那个类中:

class Plan < ApplicationRecord
  belongs_to :base_plan
  scope :order_by_code,->{ order(code: :asc) }
end

class BasePlan < ApplicationRecord
  has_many :alphabetically_ordered_plans,-> { order_by_code },class_name: "Plan"
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。