我正在使用 Ruby 1.8.7-p374 和 Rails 2.3.18。 (是的,我知道,我们正在努力。)
我正在考虑动态传递命名范围以用作 ActiveRecord 的条件。是否可以检查传递的字符串是否是记录的有效命名范围?
例如:
如果我为 Car 定义了一个名为 :red 的命名范围
named_scope :red, :condition => ["color = ?", "red"]
那有没有我可以做的功能
Car.some_function("red") # returns true
Car.some_function("blue") # returns false
提前致谢。
最佳答案
您可以使用 .respond_to?(:method)
( documentation here )
在你的情况下:
Car.respond_to?(:red) # => true
Car.respond_to?(:blue) # => false
但是你说:
I'm considering dynamically passing a named scope to be used as a condition for an ActiveRecord
我希望你不要使用这样的东西:
# url
/cars?filter=red
# controller
def index
@cars = Car.send(params[:filter]) if params[:filter].present? && Car.respond_to?(params[:filter])
@cars ||= Car.find(:all)
猜猜如果我使用这个 URL 会发生什么?
/cars?filter=destroy_all
Car
模型响应方法 .destroy_all
,因此 Ruby 在 Car 模型上调用它。 轰,所有汽车都被摧毁了!
关于ruby-on-rails - rails : Is it possible to check if a named scope is valid for a given active record?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23761723/