Ruby on rails Rails查找数据库对象
我数据库中的每个用户都有自己的名字。如何通过用户名找到用户?我试图用一种不那么愚蠢的方式来编写这个函数Ruby on rails Rails查找数据库对象,ruby-on-rails,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" LIMI
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
User.where:first\u name=>name.first
这将大致转化为:
从first_name=?
它会将参数绑定到传入的字符串。
User.where:first\u name=>name.first
这将大致转化为:
从first_name=?
它会将参数绑定到传入的字符串。假设名字不是唯一的,您可以得到所有匹配的名字,也可以只得到第一个 User.find:all,{:first\u name=>name} 或
User.find:first,{:first\u name=>name}假设名字不是唯一的,您可以得到所有匹配的名字,也可以只得到第一个 User.find:all,{:first\u name=>name} 或
User.find:first,{:first\u name=>name}应该有一个内置的,不是吗
User.find_by_first_name("Izzy")
应该有一个内置的,不是吗
User.find_by_first_name("Izzy")