數據庫中的每個用戶都有一個名字。我如何才能通過名字找到用戶?我試圖以一種不那麼愚蠢的方式編寫這個函數。查找數據庫對象對象的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