使用rails在mongodb中插入数组数据

时间:2013-06-01 18:07:18

标签: ruby-on-rails arrays mongodb mongoid

如果数据类型是数组类型

,我无法使用rails在mongodb中插入数据

以下是代码

def friend

Twitter.configure do |config|
config.consumer_key = 'GpCZ3ppx2tvOYB7mP4FONw'
config.consumer_secret = 'ectbzaP2oLPTSMGJaR5Fj6mmdgFyVsWeM9HoZ2iwaI'
config.oauth_token ='1378905500-TMtwUpl4bVpVDAcZQ29SVONITmFLL1aCzSLHDQQ'
config.oauth_token_secret = 'SIsfYHqSKfTEUD4dutaI7zYbfJQjxXmiNXiv4vWkfY'
end
@frend= Twitter.friends("shamshul2007")
@frend.each do |hell|
puts hell.name.inspect.to_s
end

#=====
fr=Array.new
@frend.each do |f|

fr.push(f)
end


#data insertion

@fri=Friend.new
@fri.username="shamshul2007"
@fri.friend=fr  
@fri.save
end

模型是friend.rb

class Friend
include Mongoid::Document
field :username, type: String
field :friend, type: Array
end

将数据推送到mongodb时出现以下错误

undefined method `__bson_dump__' for #<Twitter::User:0x007fbbec1a8538>

2 个答案:

答案 0 :(得分:0)

这段代码在做什么?

  a) @frend.each do |f|
  b)   @fri.friend=f 
  c) end

@fri.friend should be provided an array type value.

In above code snippet

  1) if "f" is an array??  --- line b)
  2) if "f" is an array then it is being overwritten each time the loop rotates. --- line b)

So check these things and should help you..

答案 1 :(得分:0)

我修复了问题,代码如下,我没有采取twitter提供的字段的子数组名称。

Twitter.configure do |config|
config.consumer_key = 's9J0L2Br1rutBCH3wBmnA'
config.consumer_secret = 'SNbrKPLRPOq8AAVXzUnwWv9OodO0iHMkYSXNa786qFs'
config.oauth_token ='1378905500-Xs9xbqSyzhtVCVUKYko1Zq1NXSz2ViHXCs0g4KA'
config.oauth_token_secret = 's9RAGElHJLIYNhTv0bwChBU4PcUHq2W9cQeWMSYt8'
end
@frend= Twitter.friends("shamshul2007")
fr=Array.new
@frend.each do |f|
fr.push(f.name)
end


#data insertion
puts "start saving"
@fri=Friend.new
@fri.username="shamshul2007"
@fri.friend=fr
@fri.save
puts "data saved"
end