2011-11-27 2 views
0

데이터베이스에있는 모든 사용자의 이름이 있습니다. 첫 번째 이름으로 사용자를 찾는 방법은 무엇입니까? 덜 바보 같은 방식으로이 함수를 작성하려고합니다.데이터베이스 객체 객체를 찾는 레일

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

나는 이것이 효과가 있다고 생각했지만 그렇지는 않습니다.

SELECT * FROM users WHERE first_name=?

을 (그리고이 매개 변수를 문자열로 바인딩 :

>> 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

처럼 보인다 통과).

0

첫 번째 이름이 고유하지 않다고 가정하면 일치하는 이름이나 처음 이름 만 가져올 수 있습니다.

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

또는

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

2

이 있어야한다 내장, 아니?

User.find_by_first_name("Izzy") 
관련 문제