[英]'scoped' method for Rails 2.X ad Rails 3
I've got a plugin I'm using for websites using Rails 2.X or Rails 3. 我有一个插件,我用于使用Rails 2.X或Rails 3的网站。
In Rails 2.3, I used a lot the 'scoped' method for complex queries : 在Rails 2.3中,我对复杂查询使用了很多“范围”方法:
p = Person.scoped({})
p = p.active
p = p.with_premium_plan if xyz
p
etc.
But I saw that it changed in Rails 3 : 但我看到它在Rails 3中发生了变化:
p = Person.scoped
etc.
So is it normal that I have to do something like that in my plugin (to be able to run it in both version of Rails), or can you suggest something nicer? 所以我必须在我的插件中执行类似的操作(能够在两个版本的Rails中运行它),或者你能提出更好的建议吗?
if Rails.version.split(".")[0] == "3"
p = Person.scoped
else
p = Person.scoped({})
end
Thanks! 谢谢! Vince
文斯
I'd really stay away from checking the literal version of Rails. 我真的远离检查Rails的文字版本。 You're just setting yourself up for failure when Rails 4 comes out.
当Rails 4出现时,你只是为自己做好准备。
If you're curious if a method takes a parameter or not, use this: 如果您对方法是否带参数感到好奇,请使用:
p = (Person.method(:scoped).arity == 1) ? Person.scoped({ }) : Person.scoped
The arity
method on a class or module returns the number of parameters required, or a negative value if it's a somewhat arbitrary number as is the case when some are optional. 类或模块上的
arity
方法返回所需参数的数量,如果它是一个有点任意的数字,则返回负值,如某些是可选的。
That being said, in Rails 2.3.8 it doesn't seem you need to pass any parameter to scoped
anyway. 话虽如此,在Rails 2.3.8中,似乎你不需要将任何参数传递给
scoped
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.