FAQ Database Discussion Community


“NoMethodError: undefined method `object' for #” Error

ruby-on-rails-4,devise,mongoid
Hello I am having an error of "NoMethodError: undefined method `information_requisition' for #" I cant seem to relate this model to my user. My code for information_requisition model is: class InformationRequisition include Mongoid::Document belongs_to :user belongs_to :admin has_many :reports And my user model is: class User include Mongoid::Document mount_uploader :avatar,...

How to have collapsed fields of a group on first load of page when rendered through rails_admin controller

ruby-on-rails,mongoid,rails-admin
I am using mongoid db. So, I group fields based on their relevance with each other. But I have too many field hence a lot many groups and during the edit action when the page load initially I want them to be collapsed but can't find a way to do...

MongoID Like query on embedded model

ruby-on-rails,mongodb,ruby-on-rails-4,mongoid
I have User model embeds_one :profile and Profile model has name. I need to run LIKE query on profile name. I tried below as suggested here User.where("profile.name" => "/.*Senthil.*/") But above solution not working. I tried lot of stock overflow answers , but no luck. Any help will be highly...

Rails, mongoid throws TypeError no implicit conversion of nil into String

ruby-on-rails,ruby,mongodb,ruby-on-rails-4,mongoid
1) I have installed MongoDB (Windows 7 64bit). Created "data/db" path and started mongod via cmd. 2) I have created Rails project by using RubiMine 7. I have added two lines for my Gemfile: gem 'mongoid' gem 'bson_ext' Then I made bundle install. 3) I have run rails generator for...

Mongodb: assert that all elements in an array have a field not null

mongodb,mongoid
Given a collection with documents like this: Task Collection document [ { "_id"=>BSON::ObjectId('54d674b64d42504b6a000000'), "submissions"=> [{"_id"=>BSON::ObjectId('54d674b64d42504b6a010000'), "grade"=>nil, "user_id"=>BSON::ObjectId('54d1e2454d42503069060000')}, {"_id"=>BSON::ObjectId('54d674b64d42504b6a020000'), "grade"=>nil, "user_id"=>BSON::ObjectId('54d1e2454d42503069070000')}, {"_id"=>BSON::ObjectId('54d674b64d42504b6a030000'), "grade"=>nil,...

Model.new is returning a Mongoid::Criteria instead of a Model instance

ruby-on-rails,mongoid
Part of my app directory setup looks like: app models tasks email_task.rb signup_task.rb task.rb task.rb contains: class Task include Mongoid::Document include Mongoid::Timestamps VALID_STATUSES = %w{ new pending complete } field :status, type: String, default: 'new' # Scopes VALID_STATUSES.each do |status| scope status.to_sym, -> { where(status: status) } define_method "#{status}?" do...

Obtain the Complement of a Scope Generated by AASM Gem in Rails

ruby-on-rails,mongoid,aasm
This question is really intended to be answered by AASM gem developers. I'm using the AASM gem in my rails app models (Mongoid). I know you automatically generate scopes for every defined state. For instance, having this... class Order include Mongoid::Document include Mongoid::Timestamps include AASM field :aasm_state aasm do state...

Mongoid preferred read replica

ruby-on-rails,mongodb,ruby-on-rails-4,mongoid,moped
I'm building a geo redundant MongoDB replica set, but there is a problem. Every time a query is sent to the database apparently a random replica is choosen. MOPED: x.x.x.0:p COMMAND database=admin command={:ismaster=>1} runtime: 148.4439ms MOPED: x.x.x.1:p COMMAND database=admin command={:ismaster=>1} runtime: 150.5547ms MOPED: x.x.x.2:p COMMAND database=admin command={:ismaster=>1} runtime: 3.8707ms MOPED:...

mongoid 4 wrong number of arguments (3 for 1) for scope

ruby-on-rails,mongoid
I trying to create the following scope: scope :involving, -> (user) do where("conversations.sender_id =? OR conversations.recipient_id =?", user.id, user.id) end but I get: wrong number of arguments (3 for 1) What I'm doing wrong. Thanks in advance....

Mongoid Search by Array of Association Id's

ruby-on-rails,mongoid,mongoid4
I have a Rails 4.2, Mongoid 4 project with these models: class Customer #aka Company include Mongoid::Document has_many :branches end class Branch include Mongoid::Document field :name, type: String, default: "" belongs_to :customer end I want to find all the Customers (aka Companies) that have a branch with name "New York"....

Get comments after the timestamp given

ruby-on-rails,ruby,timestamp,mongoid
I'm following Ryan's tutorial in polling comments and works perfectly but on polling the data he used id to get only the latest comments. How can I use the timestamp to poll the latest comments only Here's a gist link for model,controller,view,coffeescript https://gist.github.com/silvercrow27/e08c0142af43aec39f02...

rails mongoid: how to turn of persistence of nested_attributes on assign_attributes

ruby-on-rails,mongoid,persistence
Here is some simplified code: class Page include Mongoid::Document has_many :content, class_name: 'Content', dependent: destroy, autosave: false accepts_nested_attributes_for :content field :title, type: String end class Content include Mongoid::Document belongs_to :page field :text, type: String end class PagesController < ApplicationController def update @page = Page.unscoped.find(params['id']) @page.assign_attributes params.require(:page) puts @page.reflect_on_association(:content) # {:relation=>Mongoid::Relations::Referenced::Many,...

Ruby on Rails - How to delegate error messages from nested model

ruby-on-rails,ruby,ruby-on-rails-4,mongoid,paperclip
class User include Mongoid::Document has_many :images accepts_nested_attributes_for :image end class Image include Mongoid::Document include Mongoid::Timestamps include Mongoid::Paperclip has_mongoid_attached_file :uploaded_image, :path => ":rails_root/public/uploads/:class/:id/:basename.:extension", :url => "public/uploads/" validates_attachment_content_type :uploaded_file, :content_type => "application/png", :message => "error massage" belongs_to :user delegate :url, :path, to: :uploaded_image, allow_nil: true, prefix: false...

order_by in Mongoid along find_by, NoMethodError - undefined method `order_by'

ruby-on-rails,ruby,mongodb,sinatra,mongoid
I have to retrieve the mongodb records in a sinatra app using Mongoid. For this I am trying to order the records retrieved using the following query: @bin = Bin.find_by(bin_id: params[:bin_id]).order_by(:created_at.desc) But I am getting the NoMethodError, NoMethodError - undefined method `order_by' for #<Bin:0x00000101d24d60>: /Users/harshsingh/Documents/Codes/mogreet-requestbin/app.rb:79:in `block in <class:App>' /Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:1603:in `call'...

Using Mongoid: Can you use embed_in in multiple documents at the same time?

ruby,mongodb,nosql,mongoid,relationship
I'm getting use to using Mongoid, however I ran into this problem with a situation where I'm trying to use Mongoid. I have a game, the game has teams, the teams have players, and the game has the same players. class Game include Mongoid::Document embeds_many :Players embeds_many :Teams end class...

Mongoid attribute seems to not be there, but I can query by it

ruby-on-rails,mongodb,mongoid
Here's whats happening that I can display in the most succinct way possible: Model.where(:flag => false).count => 6 Model.where(:flag => false).first.flag => nil Some background: used to have an attribute field called flag on my model. Instead I changed it to has_one flag . I'm trying to run the migration...

How do you save an array of arrays in a mongoid model?

ruby-on-rails,model,mongoid
I have a response from an api that I need to save in my model which is using mongoid. I believe the response is an array of arrays and I cant seem to save it as an array or hash. Here is a sample of the response. Does anyone know...

Mongoid + RoR: Initializing the _id while create()

ruby-on-rails,mongoid
I want to get the id from one of my routes POST user/:id and create objects with that params[:id]. I don't have any intention of my application generate/ auto increment the :id when it is used as the _id. I tried: ObjectId("1").str 2015-04-23T14:22:14.888-0700 E QUERY Error: invalid object id: length...

Mongoid push new embedded document in a single query

ruby,mongodb,mongoid
We use mongoid to store a users score: class UserScore include Mongoid::Document field :user_id, type: Integer field :points, type: Integer, default: 0 embeds_many :activities end We keep track of the activities of a user by collecting them in embedded documents called activities. As the number of activities grows, the time...

Mongoid has_many relation returning fake data when enumerated

ruby-on-rails,mongodb,mongoid
I will give a quick background. I am building a directed graph in Rails with the following (summarized) models: Node has_many :edges, foreign_key: "source_id" and Edge field :source_id, :type => String field :destination_id, :type => String belongs_to :source, class_name: "Node" belongs_to :destination, class_name: "Node" I have come across 2 bizarre...

Rails mongoid regex on an Integer field

ruby,regex,mongodb,ruby-on-rails-4,mongoid
I have some IDs 214001, 214002, 215001, etc... From a searchbar, I want autocompletion with the ID "214" should trigger autocompletion for IDs 214001, 214002 Apparently, I can't just do a scope :by_number, ->(number){ where(:number => /#{number.to_i}/i) } with mongoid. Anyone know a working way of matching a mongoid Integer...

How to get all embedded mongoid documents for a user

ruby-on-rails,mongoid,mongoid4
In Mongoid (Rails) I have 3 models: File, Version and User. Version is embedded_in File, and both File and Version belongs_to a User (though not necessarily the same for all Versions in a File). Now I want to retrieve all Versions that either belong to a specific User, or are...

Mongoid::Errors::MixedRelations in AnswersController#create

ruby-on-rails,ruby,ruby-on-rails-4,mongoid
Getting following error msg while saving an answer: Problem: Referencing a(n) Answer document from the User document via a relational association is not allowed since the Answer is embedded. Summary: In order to properly access a(n) Answer from User the reference would need to go through the root document of...

Conditional default value in Rails (Mongoid) model

ruby-on-rails,mongoid
This may seem like an oxymoron, a "conditional default," but I was wondering if there is a way I can easily handle setting a default value for a field only in the case where the object is not of a certain type. For instance, I have field :object_type, type: String...

mongodb.yml for heroku using mongolab

ruby-on-rails,heroku,mongoid,mongolab
I tried to deploy my new rails app to heroku using mongolab (Only rails framework) $ rails new myapp --skip-active-record $ cd myapp b. Add gems to Gemfile ruby '2.2.0' gem 'mongoid', '~> 4', github: 'mongoid/mongoid' gem 'bson_ext' group :production do gem 'rails_12factor' end c. bundle those gems and generate...

Find Mongoid geospacial circles that contain a point

mongodb,mongoid,geospatial
I have Mongoid documents that represent services offered by local merchants. Each has one or more locations (lat/lng point) with a service area (radius). Given a customer location (lat/lng point), how can I find all the documents where the customer location falls within the service area? class Service include Mongoid::Document...

Rails Mongoid show all documents using “where”

ruby-on-rails,find,mongoid
I try to pass value as parameter, to array: Controller: @users = User.all.page(params[:page]).per(params[:per_page]).order(sort_by => sort_order).where(type: {'$all': ["#{params[:type]}"] }) Now, is it possible to find all document from collection using: .where(type: {'$all': ['something_to_find_all_from type:'] }) ?...

What is a good way to update a cache whenever a Mongoid model is saved?

ruby,mongoid
One approach would be to add an after_save callback to each model. But there are 7 models, so it would be better to put this functionality in one place. Is there a better approach? Perhaps by re-opening the Mongoid::Document module? Actually I don't think after_save would work by itself. Probably...

MongoDB - Filter and count large collections for statistics

ruby-on-rails,mongodb,mongoid
I'm using Mongoid with Rails. I have a collection called "datasets" with around 600,000 documents. Inside of each dataset there is a key "files" that may or may not exist. Inside of files there is an array of objects (files). I need to get all datasets that have files and...

How to query embedded document in rails & mongoid

ruby-on-rails,mongodb,mongoid
I have a class model, a student model and an attendance model. Attendance is embedded in Student to improve the performance. I want to show number of all students in Class, number of present students, number of absent student & percentage of attendance. I am a newbie in Mongodb and...

Is Money gem usable with Mongoid?

mongodb,mongoid,money,bigint,money-rails
It fits in the "schema" or document model files just fine as a type: Money However, any time I need the Money I get a string of a float in return. I understand it's dealing with MongoDB internally but I find my app littered with conversions of strings like BigInt.new("1.23")...

Sort by number of subdocuments mongoid

mongodb,mongoid
I have a model Person that has many Comments How could I sort people collection by number of comments Something like Person.desc(:"comments.count") ...

How make a query in to Mongoid, 'where is not null'?

ruby-on-rails,mongoid
How make a query in to Mongoid, 'where is not null'?For example where('comment_id IS NOT NULL') how make it with mongoid?...

mongoid, query with element in array

ruby,ruby-on-rails-3,mongodb,mongoid,mongodb-query
I have structure class like this: #<Transaction _id: 54d46d6a6e6f626fbcc70000, _keywords: ["1", "test1", "test2", "abc1", "projectmongo", "last2", "taka"]> array keyword map with: [field1, field2,...] So I want to query to get all transaction have field1 == "1" Is this possible? ...

Moped: get id after inserting

mongodb,mongoid,moped
When I use mongo-ruby-driver and I insert new document it returns generated '_id': db = MongoClient.new('127.0.0.1', '27017').db('ruby-mongo-examples') id = db['test'].insert({name: 'example'}) # BSON::ObjectId('54f88b01ab8bae12b2000001') I'm trying to get the '_id' of a document after doing an insertion using Moped: db = Moped::Session.new(['127.0.0.1:27017']) db.use('ruby-mongo-examples') id = db['coll'].insert({name: 'example'}) # {"connectionId"=>15, "n"=>0, "syncMillis"=>0,...

How can I turn a mongoid document into JSON stripping out embedded document ids, but keeping the main document id?

ruby,json,mongoid
I have a document that has some embedded documents (and some of those have further embedded documents). I want to return the document content as JSON but without all the IDs for the embedded documents. I can do this: mydoc.to_json(:except => :_id) but that strips all BSON IDs, including the...

Mongoid map reduce in output collection to simulate join

ruby-on-rails,mongodb,mapreduce,mongoid
I'am using mongodb/mongoid and i run two map/reduce process in two differents collections with the same key,values and return format. (like in this tutorial : http://tebros.com/2011/07/using-mongodb-mapreduce-to-join-2-collections/ ) I use the "out" option to simulate a merge between the two outputs to simulate a join operation... My "joined" collection is well...

Why can't I access instance variables inside block in Ruby?

ruby-on-rails,ruby,mongoid
I'm using Rails 4, Ruby 2.1 and mongoid as my DBMS. Inside my create method, I'm creating a fax object and sending it using Phaxio's API. I'm trying (unsuccessfully) to access attributes inside my respond_to block for various reasons. The @fax variable seems to be working, however the others aren't....

rails mongoid find parent with child

ruby-on-rails,mongoid
Fast Example, class Band include Mongoid::Document embeds_many :albums end class Album include Mongoid::Document field :name, type: String embedded_in :band end and the document will look like this, { "_id" : ObjectId("4d3ed089fb60ab534684b7e9"), "albums" : [ { "_id" : ObjectId("4d3ed089fb60ab534684b7e0"), "name" : "Violator", } ] } lets say, i want to make...

Can I use rails_admin with mongoid 4.x?

ruby-on-rails,mongodb,mongoid,rails-admin
I can't seem to find any place that confirms that it works, can I use mongoid and mongodb with rails admin? THanks...

Mongoid Query Related Collection

ruby-on-rails,mongoid
I'm trying to figure out how to query related collections in Mongoid. Here is my object model (simplified for brevity): Category ------------------- class Category include Mongoid::Document field :name, type: String ... belongs_to: product end class Product include Mongoid::Document field :name, type: String ... has_one :category end I'm trying to build...

save / update a (Moped) BSON::Document with ruby

ruby-on-rails,mongodb,mongoid,moped
I tried many ways to update an existing bson document, but it never changes in my mongodb: col = db["collection"] col.insert({"ben": 1}) doc = col.find().to_a.first # => {"_id"=>BSON::ObjectId('556c7f1b167e70640070a4d9'), "ben"=>1} first attempt to update: doc.merge!({"ben": 5, "ams": 6}) col.find().to_a.first # => {"_id"=>BSON::ObjectId('556c7f1b167e70640070a4d9'), "ben"=>1} second attempt to update: doc.update({"ben": 5, "ams": 6})...

Removing the index of a collection in mongoDB?

json,mongodb,mongoid
I want to remove the id of my document in MongoDB. I will put the document below: { "_id" : ObjectId("54f2324671eb13650e8b4569"), "nome" : "Pr.Ademar Lourenço", "tweet" : "Jornal Águas Lindas: Prefeito Hildo se reúne com governador Rollemberg e prefeitos do Entorno http://t.co/PtVWIENdO4" } I want you to be like this:...

How to quickly query multiple collections in Mongoid?

ruby,mongoid
Foo, Bar and Baz are all Mongoid collection models. There are the only collections in the DB. Is there a more efficient way to get all the data in the DB? Foo.all + Bar.all + Baz.all ...

NoMethodError in Blog::PostsController#create

ruby-on-rails,ruby,ruby-on-rails-4,mongoid,rails-routing
Note: Rails newb here. So, I recently created a Rails app with mongoid gem for use of MongoDB. I have a namespace route of :blog with a nest of resource of posts Routes.rb: Rails.application.routes.draw do namespace :blog do resources :posts end end The error comes from app/controllers/blog/posts_controller.rb: Class Blog::PostsController <...

Mongoid + RubyMoney

ruby-on-rails,ruby,mongodb,mongoid
I'm using RubyMoney (money-rails) https://github.com/RubyMoney/money-rails with Mongoid. Something like this: class Order include Mongoid::Document field :order_amount, :type => Money, :default => Money.new(0) ... end How can I aggregate on a Money field? For example, when I run Order.sum(:order_amount), I get 0 even if the field has a value like #<Money...

Solved: Trouble updating a document that has both belongs_to and has_many associations

ruby-on-rails,mongodb,mongoid,nomethoderror
I'm having trouble with my Rails/Mongoid app whenever I'm updating my documents. I'm at my wits' ends and I could use some help. I have three collections: owners, vessels and modifications. class Owner include Mongoid::Document has_many :vessels field :name, type: String field :uprn, type: String end class Vessel include Mongoid::Document...

How to programmatically access Mongoid's config?

ruby-on-rails,configuration,mongoid
Specifically, I want to read the hosts value of the current Mongoid config. Is that possible? I'm using Mongoid with Ruby on Rails....

Mongoid HABTM relationships across embedded documents

ruby-on-rails,ruby-on-rails-4,mongoid,embedded-documents
I'm trying to create a Mongoid N-N reference association between two embedded documents in Rails 4 however I'm finding it difficult to get my head round how this is done. I started by adding the HABTM association to the relevant models below (Track and Option) but of course I'm getting...

MongoDB service not working after upgrade to Ubuntu 15.04

mongodb,ubuntu,mongoid,systemd
I have recently upgraded my ubuntu from 14.10 to 15.04. All features seems to be working fine except MongoDB. I am using mongoDB with ruby on rails application using Mongoid gem. MongoDB is not controllable from service as we do normally in ubuntu. sudo service mongodb start or sudo service...

simple_form_for with localized, scoped routes and Mongoid (missing required keys: [:id])

ruby-on-rails,mongoid,simple-form,rails-i18n
I have a _form.html.haml partial for a model FileType that I want to render in my new.html.haml and edit.html.haml view. = simple_form_for [:document_manager, file_type] do |f| ... When I render this partial in the new view, this works, but when I render it in the edit view, simple_form tries to...

Undefined method `reset_counters' for Mongoid 3.1.6

ruby-on-rails,mongoid,mongoid3,counter-cache
I just updated my mongoid to version 3.1.6, so that I could use the reset_counters method to keep track of my model relations. But just as I did before the gem update I still get this error: undefined method `reset_counters' for Mongoid::Persistence::Atomic::Operation:Module In my Gemfile I have this version: gem...

How to validate that an array is not empty in Mongoid?

ruby-on-rails,ruby,mongoid,activemodel,activesupport
class Foo include Mongoid::Document field :bars, type:Array end How to validate that the bars array is not empty?...

Mongoid speed get slower when order by created_at

ruby-on-rails,performance,mongoid
@statuses = @server.statuses.where(:created_at => 1.days.ago..Time.now).to_a I getting statuses with this code. But when I executed this code, it make many delay. How can I solve? My data inserted every 5 minutes....