2011-11-27 82 views
0

数据库中的每个用户都有一个名字。我如何才能通过名字找到用户?我试图以一种不那么愚蠢的方式编写这个函数。查找数据库对象对象的Rails

def find_by_name(name) 
    User.find_each{|u| 
    return u if u.first_name == name 
    } 
    return nil 
end 

我以为这会工作,但事实并非如此。

>> u = User.first 
User Load (0.2ms) SELECT "users".* FROM "users" LIMIT 1 
=> #<User id: 41, first_name: "Justin", last_name: "Bieber", created_at: "2011-11-13 23:13:23", updated_at: "2011-11-13 23:13:23"> 
>> u = User.first(:first_name => "Justin") 
ArgumentError: Unknown key: first_name 
from /Library/Ruby/Gems/1.8/gems/activesupport-3.1.1/lib/active_support/core_ext/hash/keys.rb:44:in `assert_valid_keys' 
from /Library/Ruby/Gems/1.8/gems/activesupport-3.1.1/lib/active_support/core_ext/hash/keys.rb:43:in `each_key' 
from /Library/Ruby/Gems/1.8/gems/activesupport-3.1.1/lib/active_support/core_ext/hash/keys.rb:43:in `assert_valid_keys' 
from /Library/Ruby/Gems/1.8/gems/activerecord-3.1.1/lib/active_record/relation/spawn_methods.rb:123:in `apply_finder_options' 
from /Library/Ruby/Gems/1.8/gems/activerecord-3.1.1/lib/active_record/relation/finder_methods.rb:119:in `first' 
from /Library/Ruby/Gems/1.8/gems/activerecord-3.1.1/lib/active_record/base.rb:441:in `__send__' 
from /Library/Ruby/Gems/1.8/gems/activerecord-3.1.1/lib/active_record/base.rb:441:in `first' 
from (irb):8 

我的模型看起来像这样

class User < ActiveRecord::Base 
    has_many :photos 
end 

回答

3

User.where(:first_name => name).first

这将大致翻译成这样:

SELECT * FROM users WHERE first_name=?

(它将参数绑定到字符串通过)。

0

假设名字不是唯一的,你可以得到所有匹配的或只是第一个。

User.find(:all, {:first_name => name})

User.find(:first, {:first_name => name})

2

应该有一个内置的,不是吗?

User.find_by_first_name("Izzy")