Ruby on rails 覆盖ActiveRecord查找
我已经在Rails 2.3.10和3.0.3中完成了这项工作,它可以正常工作Ruby on rails 覆盖ActiveRecord查找,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我已经在Rails 2.3.10和3.0.3中完成了这项工作,它可以正常工作 def self.find(*args) records = super # Manipulate Records here. end 我正在Rails 3中寻找一个基本查找器函数,我可以将其替换为应用于Post.all、Post.first、Post.last等功能。all、first和last都只是find的包装,因此重新定义find应该会影响所有这些功能。看看它们是如何在中实现的。all、first
def self.find(*args)
records = super
# Manipulate Records here.
end
我正在Rails 3中寻找一个基本查找器函数,我可以将其替换为应用于Post.all、Post.first、Post.last等功能。
all
、first
和last
都只是find
的包装,因此重新定义find
应该会影响所有这些功能。看看它们是如何在中实现的。all
、first
和last
都只是find
的包装,因此重新定义find
应该会影响所有这些。看看它们是如何在中实现的。我相信您正在寻找:
# File activerecord/lib/active_record/relation/finder_methods.rb, line 95
def find(*args)
return to_a.find { |*block_args| yield(*block_args) } if block_given?
options = args.extract_options!
if options.present?
apply_finder_options(options).find(*args)
else
case args.first
when :first, :last, :all
send(args.first)
else
find_with_ids(*args)
end
end
end
我相信你正在寻找这个:
# File activerecord/lib/active_record/relation/finder_methods.rb, line 95
def find(*args)
return to_a.find { |*block_args| yield(*block_args) } if block_given?
options = args.extract_options!
if options.present?
apply_finder_options(options).find(*args)
else
case args.first
when :first, :last, :all
send(args.first)
else
find_with_ids(*args)
end
end
end
我的建议。。。改为使用范围或类方法来执行此操作: e、 g 然后申请
TheClass.my_scope.all
TheClass.my_scope.first
TheClass.my_scope.last
我的建议。。。改为使用范围或类方法来执行此操作: e、 g 然后申请
TheClass.my_scope.all
TheClass.my_scope.first
TheClass.my_scope.last
这将符合原始问题的要求
def self.find_by_sql(*args)
records = super
# Manipulate Records here
return records
end
这将符合原始问题的要求
def self.find_by_sql(*args)
records = super
# Manipulate Records here
return records
end
像这样修改核心功能几乎从来都不是一个好主意。这在一个坏的方面是令人惊讶的。你能给出一些你想要达到的目标的背景吗?可能有一个更干净、更易于维护的解决方案。像这样修改核心功能几乎从来都不是一个好主意。这在一个坏的方面是令人惊讶的。你能给出一些你想要达到的目标的背景吗?可能有一个更干净、更易维护的解决方案。查找覆盖工作正常,但由于某些原因,它似乎不能在所有情况下工作,不管是第一个还是最后一个。我会再试一次。查找覆盖工作很好,但由于某些原因,它似乎不适合所有人,无论是第一个还是最后一个。我会再试一次。