mongoid-indifferent-access
mongoid-indifferent-access copied to clipboard
Not working in Rails 4. NoMethodError for `fetch` and `with_indifferent_access`
Gemfile
gem 'mongoid', '~> 4.0.0.beta1', github: 'mongoid/mongoid'
gem 'mongoid-indifferent-access', require: "mongoid_indifferent_access"
Model
class ServerdensityInstance
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Extensions::Hash::IndifferentAccess
# Fields and methods and stuff
end
First Attempt
Controller Action
def show
if ServerdensityInstance.where(serverdensity_id: params[:id]).exists?
@imported = true
@instance = ServerdensityInstance.find_by(serverdensity_id: params[:id])
else
@imported = false
@instance = server_density.fetch_instance(params[:id])
end
end
Which caused this error
NoMethodError at /servers/serverdensity/530074dcba6d13045777c0e6
undefined method `fetch' for #<ServerdensityInstance:0x007fb8dbcf5580>
The error placement in the view
- if @instance["providerId"].present?
small = @instance["providerId"]
- elsif @instance["_id"].present? <<<<<<<<
small= @instance["_id"]
But the @instance property is set as it should be.
@instance
#<ServerdensityInstance _id: 532cccfb5468653c69000000, ...<redacted>...
Second Attempt
I even tried to access it indirectly
instance = ServerdensityInstance.find_by(serverdensity_id: params[:id])
@instance = instance.with_indifferent_access
But that prompted this error:
NoMethodError at /servers/serverdensity/530074dcba6d13045777c0e6
undefined method `with_indifferent_access' for #<ServerdensityInstance:0x007fb8dbc2ed68>
Question
I am up a creek without a paddle here. I am sure there is something simple I am doing wrong. Can anyone provide me any insight?
Edit: Fixed
I spent a while churning through Mongoid's documentation and found the instance method attributes which resides on all documents and returns the document as HashWithIndifferentAccess. So,
This
ServerdensityInstance.find_by(serverdensity_id: params[:id])
Became this
ServerdensityInstance.find_by(serverdensity_id: params[:id]).attributes
But still, I would really rather use this awesome gem to eliminate the need for having to call attributes on every.single.document that I get back from MongoDB. :( I'm stuck.