覆盖has_many关联获取器 [英] Overriding a has_many association getter

查看:56
本文介绍了覆盖has_many关联获取器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户可以拥有多辆汽车-

A user can have several cars -


  • 用户:has_many:cars

  • 汽车:belongs_to:user

  • User: has_many :cars
  • Car: belongs_to :user

每次我呼叫 @ user.cars 时,它都会以默认搜索顺序返回汽车的列表。

Every time I call @user.cars it returns the list of cars in default search order.

如果我希望关联在任意字段上排序,我可以这样做

If I wanted the association sorted on some arbitrary field, I could do

class User < ActiveRecord::Base
  has_many :cars, -> { order :num_wheels }
end

但是让我说我​​的订购逻辑很复杂,我想只是重写关联获取器以实现我自己的逻辑

But let's say my ordering logic is complex and I want to just override the association getter to implement my own logic

我尝试类似-

class User < ActiveRecord::Base
  has_many :cars

  def cars
    # Pretend this is complex logic
    cars.order(:num_wheels)
  end
end

但是,这显然失败了,因为您无法引用原始的汽车从覆盖的 cars 方法内部,而不会无限循环。

However that obviously fails because you can't reference the original cars from inside the overridden cars method without it looping infinitely.

是否可以从覆盖的吸气剂内部引用原始吸气剂?

Is there a way to reference the "original" getter from inside my overridden getter?

谢谢!

推荐答案

使用超级:

class User < ActiveRecord::Base
  has_many :cars

  def cars
    # Pretend this is complex logic
    super.order(:num_wheels)
  end
end

当您使用像has_many这样的宏时,Rails动态创建一个模块(可以由在您的情况下,请定义访问器和读取器(在您的情况下,例如汽车,可以由User.genic_association_methods.instance_methods访问)。该模块成为您的User类的祖先,因此您可以在自己的cars方法中通过 super访问reader方法。

when you use a macro like has_many, Rails dynamically creates a module(which could be accessed by User.generated_association_methods).In your case, define the accessors and readers(such as "cars" in your case, which could be accessed by User.generated_association_methods.instance_methods). This module becomes the ancestor of your User class, so you can access the reader method(cars) by "super" in your own cars method.

这篇关于覆盖has_many关联获取器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆