Cam*_*mel 0 ruby ruby-on-rails mongoid
我想从mongoid中使用这个函数:
person.update_attributes(first_name: "Jean", last_name: "Zorg")
Run Code Online (Sandbox Code Playgroud)
但我想从另一个变量传递所有属性.我怎么做?
编辑:谢谢大家的回复.我是红宝石的新手,所以起初我以为我犯了一个愚蠢的错误.错误是在一个完全不同的地方,正确的代码,为您的乐趣:
def twitter
# Scenarios:
# 1. Player is already signed in with his fb account:
# we link the accounts and update the information.
# 2. Player is new: we create the account.
# 3. Player is old: we update the player's information.
# login with a safe write.
puts "twitter"
twitter_details = {
twitter_name: env["omniauth.auth"]['user_info']['name'],
twitter_nick: env["omniauth.auth"]['user_info']['nickname'],
twitter_uid: env["omniauth.auth"]['uid']
}
if player_signed_in?
@player = Player.find(current_player['_id'])
else
@player = Player.first(conditions: {twitter_uid: env['omniauth.auth']['uid']})
end
if @player.nil?
@player = Player.create!(twitter_details)
else
@player.update_attributes(twitter_details)
end
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Twitter"
sign_in_and_redirect @player, :event => :authentication
end
Run Code Online (Sandbox Code Playgroud)
该update_attributes方法采用Hash参数,因此如果你有一个哈希,h只需:first_name和:last_name键然后:
person.update_attributes(h)
Run Code Online (Sandbox Code Playgroud)
如果你的Hash有更多的键,那么你可以slice用来拉出你想要的键:
person.update_attributes(h.slice(:first_name, :last_name))
Run Code Online (Sandbox Code Playgroud)
如果你看一下Mongoid的源代码,你会看到update_attributes文件中
的定义.rvm/gems/ruby-1.9.2-p0/gems/mongoid-2.3.1/lib/mongoid/persistence.rb
# Update the document attributes in the datbase.
#
# @example Update the document's attributes
# document.update_attributes(:title => "Sir")
#
# @param [ Hash ] attributes The attributes to update.
#
# @return [ true, false ] True if validation passed, false if not.
def update_attributes(attributes = {})
write_attributes(attributes); save
end
Run Code Online (Sandbox Code Playgroud)
它需要一个哈希 - 这意味着你可以使用哈希作为传入的变量.例如
my_attrs = {first_name: "Jean", last_name: "Zorg"}
person.update_attributes( my_attrs )
Run Code Online (Sandbox Code Playgroud)