Rails查找数据库对象

时间:2011-11-27 22:35:51

标签: ruby-on-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 个答案:

答案 0 :(得分:3)

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

这将大致转化为:

SELECT * FROM users WHERE first_name=?

(它会将参数绑定到传入的字符串)。

答案 1 :(得分:2)

应该有一个内置的,没有?

User.find_by_first_name("Izzy")

答案 2 :(得分:0)

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

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

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