带有Mongoid的Array的值

时间:2016-08-08 18:15:47

标签: ruby-on-rails mongoid

我正在做用户之间的关系,现在我想要使用Mongoid来访问embedded_in文档中的值,生成类似这样的东西,我需要好友列表:

>> 

current_user

=> #<User _id: BSON::ObjectId('57a4df6927d8754bd68aaade'), contacts: [{"_id"=>BSON::ObjectId('57a4df7a27d8754bd68aaadf'), "created_at"=>Fri, 05 Aug 2016 18:48:26 UTC +00:00, "friendlist"=>[BSON::ObjectId('57a4df6927d8754bd68aaade'), BSON::ObjectId('5790f58a27d8757b4ff547fd'), BSON::ObjectId('5790f43727d87576358ae575')], "owner"=>"57a4df6927d8754bd68aaade", "updated_at"=>Fri, 05 Aug 2016 18:48:26 UTC +00:00}], created_at: Fri, 05 Aug 2016 18:48:09 UTC +00:00, email: "testauth@myApp.com", haveFiles: false, image: nil, location: nil, updated_at: Mon, 08 Aug 2016 15:39:31 UTC +00:00, username: "testauth">

这里我需要的一行:

"friendlist"=>[BSON::ObjectId('57a4df6927d8754bd68aaade'), BSON::ObjectId('5790f58a27d8757b4ff547fd'), BSON::ObjectId('5790f43727d87576358ae575')]

我的代码看起来像这样

class MainController < ApplicationController
  def index
    @listofusers = User.all
    User.find_by(id: current_user.id).where(contacts: [friendlist]) do |listofcontacts|
      puts "***list of contacts***"
      puts listofcontacts
    end
  end
end

模型

用户

## Customable ;)
  field :username, :type => String
  field :haveFiles, :type => Boolean, default: false
  field :location, :type => String
  field :image, :type => String
  embeds_many :contacts 
  embeds_many :favlists
  # Validate the presence of type username
  validates_presence_of :username

联系

class Contact
  include Mongoid::Document
  include Mongoid::Timestamps
  field :owner, :type => String
  field :friendlist, :type => Array
  embedded_in :users
end

1 个答案:

答案 0 :(得分:0)

我想你想这样做:

class MainController < ApplicationController
  def index
    @listofusers = User.all
    puts "***list of contacts***"
    User.in(contacts: current_user.id) do |user|
      puts user
    end
  end
end

如果contactsBSON::ObjectId的数组,这将有效。如果错了,请纠正我。