2011-11-07 64 views
0

我想要使用此功能從mongoid:傳遞屬性Mongoid update_attributes方法()

person.update_attributes(first_name: "Jean", last_name: "Zorg") 

但我想從另一個變量的所有屬性通過。我怎麼做?

編輯:謝謝大家的回覆。我是新來的紅寶石,所以起初我以爲我只是犯了一個愚蠢的錯誤。該缺陷是在一個完全不同的地方,正確的代碼,爲您的享受:

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

您在哈希擁有姓氏和名字? –

+0

是的(我有他們在散列) – CamelCamelCamel

+1

不理解這一點,無論是。如果你在一個變量中有一個哈希集,你可以將這個哈希函數傳遞給函數...... – WattsInABox

回答

5

如果你看一下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 

它需要一個哈希表 - 這意味着你可以使用哈希作爲傳入的變量。 eg

my_attrs = {first_name: "Jean", last_name: "Zorg"} 

person.update_attributes(my_attrs) 
6

update_attributes方法接受一個哈希參數,因此,如果你有一個Hash,h,只有:first_name:last_name鍵則:

person.update_attributes(h) 

如果你的散列有多個鍵,那麼你可以使用slice來拉出你想要的:

person.update_attributes(h.slice(:first_name, :last_name)) 
2

什麼發生在update_attributes方法和ind在整個Rails平臺上,變量在必要時會在內部放入哈希中。

所以下面的是等價的:

person.update_attributes(first_name: "Jean", last_name: "Zorg") 
person.update_attributes({first_name: "Jean", last_name: "Zorg"}) 
person.update_attributes(name_hash) 

其中name_hash是:

name_hash = {first_name: "Jean", last_name: "Zorg"}