Search code examples
ruby-on-railsmongodbruby-on-rails-4mongoidmongoid4

rails-4 mongoid-4 query to find all record gives undefined method `to_sym' for nil:NilClass


I am using Rails 4.1.4, Mongoid 4.0 and ruby 2.1.2p95. From my controller index that always returns undefined method `to_sym' for nil:NilClass. There are records in the database and from rails console, running thesame command @email_templates = EmailTemplate.all.to_a returns all the record in the database.

This is the controller index

 class EmailTemplatesController < ApplicationController

    def index
       @email_templates = EmailTemplate.all.to_a
    end
  end

A shortened version of the Model

  class EmailTemplate
   include Mongoid::Document
   field :name, type: String
   field :subject, type: String
   field :from, type: String
   field :to, type: String
   field :body, type: String
   field :template, type: BSON::Binary
  end

Why is this @email_templates = EmailTemplate.all.to_a working in rails console but returning error when called from the controller's index action.


Solution

  • It turned out the problem was in my mongoid.yml not properly picking the database settings passed in via rails 4.1 secrets.yml file.

    so instead of this in my config/secrets.yml file

      default: &mongodb
      mongodb_host: <%= ENV['TRG_MONGODB_HOST'] %>
      mongodb_host_port: <%= ENV['TRG_MONGODB_HOST_PORT'] %>
      mongodb_database: <%= ENV['TRG_MONGODB_DATABASE'] %>
      mongodb_db_username: <%= ENV['TRG_MONGODB_DB_USER'] %>
      mongodb_db_passowrd:  <%= ENV['TRG_MONGODB_DB_PASSWORD'] %>
    
      development:
        secret_key_base: xxxxxxxxyyyy
        <<: *mongodb
    

    we have this, with the database settings keys prefixed with symbol in config/secrets.yml file like this:

      default: &mongodb
      :mongodb_host: <%= ENV['TRG_MONGODB_HOST'] %>
      :mongodb_host_port: <%= ENV['TRG_MONGODB_HOST_PORT'] %>
      :mongodb_database: <%= ENV['TRG_MONGODB_DATABASE'] %>
      :mongodb_db_username: <%= ENV['TRG_MONGODB_DB_USER'] %>
      :mongodb_db_passowrd:  <%= ENV['TRG_MONGODB_DB_PASSWORD'] %>
    

    As you can see, I was passing the config from the secrets.yml file to the mongoid.yml or database.yml file the wrong way by using.

     Rails.application.secrets.mongodb_db_username
    

    instead of using embedded ruby like this:

     <%= Rails.application.secrets.mongodb_db_username %>
    

    The final uri in the mongoid.yml now looks like this:

     uri: mongodb://<%= Rails.application.secrets.mongodb_db_username %>:<%= Rails.application.secrets.mongodb_db_password %>@<%= Rails.application.secrets.mongodb_host %>:<%= Rails.application.secrets.mongodb_host_port %>/<%= Rails.application.secrets.mongodb_database %>