2011-11-27 63 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")