Rails 3 中是否有更简单的方法来查找记录并返回其属性之一?
我发现自己一遍又一遍地编写以下代码:
MyModel.find(my_id).my_field
我想知道是否有更简单的方法来编写此代码?
I found myself writing the following piece of code over and over again:
MyModel.find(my_id).my_field
I wonder if there is a simpler method to write this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您问是否有更简洁的书写方式……不确定标准查找器是否有。你拥有的东西相当小。只是为了好玩,我为你写了这个:)
如果你把它作为像crazy_finder.rb这样的文件放在你的配置/初始化程序中,那么你可以说:
它并没有为你节省太多,但只是觉得写起来会很有趣。
If you are asking if there is more concise way of writing that.. not sure there is with the standard finders. What you have is pretty small. Just for fun I wrote this for you though :)
If you put this in your config/initializers as some file like crazy_finder.rb you can then just say:
It doesnt save you much, but just thought it would be fun to write.
除了 Jake 针对每个模型和每个属性的全局解决方案之外,您还可以轻松定义显式的单独访问器:
或字段数组:
In addition to Jake's global solution for every model and every attribute, you can easily define explicit individual accessors:
Or an array of fields:
您是一遍又一遍地对同一资源执行此操作还是对许多不同的资源执行此操作?如果您能为我们提供更好的示例来说明您正在尝试做的事情,那将会非常有帮助,如果您多次这样做,这将有助于为我们提供您多次所做的事情的示例。
如果您对一个资源执行此操作只是为了获得不同的值:
如果您在同一操作中一遍又一遍地执行此操作,那么您就做错了。首先将结果存储在一个变量中,如下所示:
然后你可以使用
然后再次(无需再次查找)
或者如果您想对集合执行此操作,您可以执行以下操作:
等..你身边更好的例子将有助于帮助你!
Are you doing this for same resource over and over again or to many different resources? It would really help if you'd give us better example of what you're trying to do, if you're doing that many times, it would help to give us example of what you're doing many times.
If you're doing this for one resource only to get different values:
If you're doing this in same action over and over again, you're doing it wrong. First store your result in a variable like this:
and then you can use
and then again (without the need to find it again)
or if you want to do this for a collection you can do:
etc.. better example from your side would help to help you!