2013-02-22 42 views
2

有沒有辦法將燈具轉換爲一組ActionController :: Parameters?Rails 3:將燈具轉換爲一組ActionController ::參數

例如:

# contacts.yml 

dan: 
    first_name: Dan 
    last_name: Gebhardt 
    email: [email protected] 
    notes: Writes sample code without tests :/ 

joe: 
    first_name: Joe 
    last_name: Blow 
    email: [email protected] 
    notes: Lousy plumber 

# contacts_test.rb 

@dan = contacts(:dan) 
# create params that represent Dan? 
@dan_as_params = ActionController::Parameters.new(???) 

任何及所有的幫助表示讚賞。

回答

2

你可以把對象變成JSON和回散含正確PARAM鍵這樣的:

h= Hash[*JSON.load(@dan.to_json).map{ |k, v| [k.to_sym, v] }.flatten] 
params= {contact: h} 

更新:

你也可以使用JSON.parse

dan= Hash[*JSON.parse(@dan.to_json, symbolize_names: true).flatten] 
params= {contact: dan} 

其中有它自己將json鍵轉換爲符號的內部方式。