开发者

rails3 shortcut

Previously I used to do

project = Project.find_by_name('foo')

Now rails3 has better syntax so I started using

project = Project.where(:name => 'foo').limit(1).first
开发者_运维问答

However this new style is too verbose. Is there a shortcut I should know of.


The first one should still work. Does it not?


Adding a .limit(1) is redundant; calling the .first method already does this for you. Like the other answer mentions, the first style should still work perfectly fine and is not deprecated.


how about using a named scope?

scope :find_foo, where(:name => 'foo').limit(1).first

then just do

Project.find_foo

of course you can make it dynamic using lambda

http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html


What's wrong with just

project = Project.where(:name => 'foo')

You didn't have a limit on the find_by_name so I assume names are unique.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜