我正在尝试将此响应从API保存到模型字段。我不能保存它,因为mongoid说这不是一个字符串。我尝试将其保存为数组和哈希。没有运气。
如何正确地将其保存在字段中或正确格式化,以便我可以将其保存为数组或散列,以便稍后调用它。我想可能是这样的但是感觉不对。
transactions.rb
field :accounts, type: Array.new
...
def account_pull
accounts_response = Api.set_user(access_token, ['auth'])
self.accounts = accounts_response.accounts
model.save
end
end
以下是我收到的完整回复的示例。
#<Api::User:0xb7e9f2c @accounts=[#<Api::Account:0xb7b6eb0 @id="QPO8Jo8vdDHMepg41PBwckXm4KdK1yUdmXOwK", @name=nil, @type="depository", @meta={"number"=>"9606", "name"=>"Bank Savings"}, @institution_type="fake_institution", @available_balance=1203.42, @current_balance=1274.93, @subtype=nil, @numbers={"routing"=>"021000021", "account"=>"9900009606", "wireRouting"=>"021000021"}>, #<Api::Account:0xb7b6ba4 @id="nban4wnPKEtnmEpaKzbYFYQvA7D7pnCaeDBMy", @name=nil, @type="depository", @meta={"number"=>"1702", "name"=>"Bank Checking"}, @institution_type="fake_institution", @available_balance=1081.78, @current_balance=1253.32, @subtype=nil, @numbers={"routing"=>"021000021", "account"=>"9900001702", "wireRouting"=>"021000021"}>, #<Api::Account:0xb7b68e8 @id="XARE85EJqKsjxLp6XR8ocg8VakrkXpTXmRdOo", @name=nil, @type="depository", @meta={"number"=>"5204", "name"=>"Bank Premier Checking"}, @institution_type="fake_institution", @available_balance=7205.23, @current_balance=7255.23, @subtype=nil, @numbers={"routing"=>"021000021", "account"=>"9900005204", "wireRouting"=>"021000021"}>, #<Api::Account:0xb7b66cc @id="pJPM4LMBNQFrOwp0jqEyTwyxJQrQbgU6kq37k", @name=nil, @type="credit", @meta={"limit"=>12500, "number"=>"3002", "name"=>"Bank Credit Card"}, @institution_type="fake_institution", @available_balance=9930, @current_balance=2275.58, @subtype=nil, @numbers={}>], @transactions=[], @permissions=["auth"], @access_token="test_chase", @api_res="success", @info={}, @pending_mfa_questions="", @type=nil>
答案 0 :(得分:1)
试试此代码
将帐户字段类型更改为哈希
class Transactions
include Mongoid::Document
field : accounts :type => Hash
end
然后您可以在转换为哈希
后保存响应 def account_pull
response = Api.set_user(access_token, ['auth'])
accounts = response.accounts
accounts_hash = Hash[accounts.map.with_index { |x, i| [i, x] }]
self.accounts = accounts_hash
self.save
end
答案 1 :(得分:1)
你的回复既不是字符串也不是数组或哈希:它是一个带有API :: Account数组的API :: User。
使用as_json将它转换为一个简单的结构可以解决这个问题:
model.user = api_user.as_json
model.save
或者,您可以尝试获取初始响应,以避免许多转换(如果可能)。