gpt4 book ai didi

ruby-on-rails - 定义一个方法来捕获类中的a_method[]

转载 作者:太空宇宙 更新时间:2023-11-03 17:26:43 24 4
gpt4 key购买 nike

我有很多这样的电话:

User.active[0..5]

哪个调用:

class User
def active
(an ActiveRelation)
end
end

出于性能原因,我正在尝试做这样的事情:

class User
def active[limit]
(an ActiveRelation).limit(limit.to_a.size)
end
end

不幸的是它不起作用,有什么想法可以实现吗?

== 编辑

更清洁:

class RelationWithLimit < ActiveRecord::Relation
def [] selector
case selector
when Integer
self.offset(selector).limit(1)
when Range
self.offset(selector.to_a[0]).limit(selector.to_a.size)
end
end
end

class ActiveRecord::Base
private
def self.relation #:nodoc:
@relation ||= RelationWithLimit.new(self, arel_table)
finder_needs_type_condition? ? @relation.where(type_condition) : @relation
end
end

最佳答案

您可以拥有自己的 ActiveRelation 特殊子类

class UserReturnRelation < ActiveRecord::Relation
def [] lim
self.limit lim
end
end

class User
def active
# Without knowing exactly what relation you are using
# One way to instantiate the UserReturnRelation for just this call
UserReturnRelation.new(self, arel_table).where("state = active")
end
end

然后 User.active[5] 应该按预期工作。

编辑:添加了实例化信息。你可能想看看 Base#scopedBase#relation了解更多信息

关于ruby-on-rails - 定义一个方法来捕获类中的a_method[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7258956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com