I have a requirement to convert an ActiveRecord model class into a MongoDB Document class automatically. I am able to do so using a rails generator which will read the attributes of a model and generate the new document.rb.
If a ActiveRecord model class looks like below:
class Project < ActiveRecord::Base
attr_accessible :completed, :end_date, :name, :start_date
end
Then, a generated class confirming to Mongoid's structure will be as below:
class ProjectDocument
field :name, type: String
field :start_date, type: Date
field :end_date, type: Date
field :completed, type: Boolean
field :created_at, type: Time
field :updated_at, type: Time
end
But I don't want to store a different document files, one for each model. I want to be able to generate this document class on the fly, whenever the rails application is started.
Is this possible? Is this approach of generating and using classes from memory advised? I don't have constraints on changes to AR model structure; the document is flexible w.r.t data structure and changed columns will get added automatically.
My first attempt would look something like this:
klass = Project
new_class = Object.const_set(klass.name + "Document", Class.new)
klass.columns.each do |c|
new_class.class_eval do
field c.name.to_sym, type: c.type
end
end
You'll almost certainly have to do something more complicated to set the field type correctly, but this should give you a good starting point.
Related
My application model allows Patients to have CustomFields. All patients have the same customs fields. Customs fields are embedded in the Patient document. I should be able to add, update and remove custom fields and such actions are extended to all patients.
class Patient
include Mongoid::Document
embeds_many :custom_fields, as: :customizable_field
def self.add_custom_field_to_all_patients(custom_field)
Patient.all.add_to_set(:custom_fields, custom_field.as_document)
end
def self.update_custom_field_on_all_patients(custom_field)
Patient.all.each { |patient| patient.update_custom_field(custom_field) }
end
def update_custom_field(custom_field)
self.custom_fields.find(custom_field).update_attributes({ name: custom_field.name, show_on_table: custom_field.show_on_table } )
end
def self.destroy_custom_field_on_all_patients(custom_field)
Patient.all.each { |patient| patient.remove_custom_field(custom_field) }
end
def remove_custom_field(custom_field)
self.custom_fields.find(custom_field).destroy
end
end
class CustomField
include Mongoid::Document
field :name, type: String
field :model, type: Symbol
field :value, type: String
field :show_on_table, type: Boolean, default: false
embedded_in :customizable_field, polymorphic: true
end
All pacients have the same customs fields embedded in. Adding a custom field works very well. My doubt is about updating and destroying.
This works, but it is slow. It makes a query for each pacient. Ideally I would just be able to say to MongoDB 'update the document with id: that is embedded in the array *custom_fields* for all documents in the Patient collection'. Idem for destroy.
How can I do this in Mongoid?
I am using Mongoid 3.1.0 & Rails 3.2.12
I don't think there is a way you can do that with a good efficiency with embedded documents.
Maybe you should consider having a referenced relationship between your models, so that you can use the delete_all and update_all methods on the collection.
Here's my use case:
I've got a collection full of sales tax rates that have been imported from CSV files. I created the Mongoid model to mirror the field names (these are not changeable):
class SalesTaxRate
include Mongoid::Document
field :state, type: String
field :zip_code, type: String
field :tax_region_name, type: String
field :tax_region_code, type: String
field :combined_rate, type: Float
end
Next, I'm building a model for use in my app. Let's say I want to create something called a Location:
class Location
include Mongoid::Document
field :name, type: String
field :street, type: String
field :city, type: String
field :state, type: String
field :zip_code, type: String
end
I'd like to be able to get a location's sales tax rate simply by calling something like this:
home = new Location(...)
home.sales_tax_rate
I'll never be setting the rate via home, just looking it up.
What's the "right" way to do this? I can think of two approaches -- the simple way seems to be just to define a method that does the lookup, as so:
class Location
...
def sales_tax_rate
SalesTaxRate.where(zip_code: self.zip_code).first.combined_rate
end
And this works. But I'm wondering whether I should be using a belongs_to association and, if so, why and how best to do that.
Still learning the ropes here, so apologies if this is a novice/silly question. Many thanks in advance!
If you have an index on zip_code in model SalesTaxRate what you are doing is essentially the same as what belongs_to will do. Just have a nil check in your code to ensure that it doesn't fail:
SalesTaxRate.where(zip_code: self.zip_code).first.try(:combined_rate)
# or
rate = SalesTaxRate.where(zip_code: self.zip_code).first
rate.nil? ? nil : rate.combined_rate
If you still want to go belongs_to route, you can define zip_code to be the identity in your SalesTaxRate. But you should take care of few things if you do that: First, all the zip codes in imported data need to be unique. Second, your location model can not have any zip code which is not available in SalesTaxRate otherwise you will face issues.
I started to use the mongoid gem in my project, and I'm a little confused about how it store and get the information on the database. I have fields of specifics types in my models, but when I get it from the DB it returns a Hash.
Here is my models:
service.rb
class Service
include Mongoid::Document
field :username, type: String
field :strategy, type: Strategy
field :design, type: Design
end
strategy.rb
class Strategy
include Mongoid::Document
field :name, type: String
field :description, type: String
field :resources, type: Resources
field :scalability, type: Scalability
field :localization, type: Localization
field :contact, type: Contact
end
If I initialize a new service #service, and do #service.class it returns Service, the right one, but if I try do #service.strategy.class, it returns Hash, and not Strategy, like I was expecting. I read on the mongoid manual there are the "Custom field serialization", what I think allows me to do what I want. But I was wondering if there are not any other way to do that easily, because I have lots of models to change.
This is my 2nd day playing with Ruby on Rails, so please be gentle :)
I have a very (hopefully) simple question: I want to set a publish date on my model, when it is indeed being created. I am using Mongoid, and it looks like this:
class Page
include Mongoid::Document
field :content, type: String
field :title, type: String
field :published_on, type: DateTime
end
Here is the question: should I set the published_on field from the create action, just before the call to #page.save? Or is there a better, more idiomatic way?
If I do it like that, meaning, calling #page.published_on = Date.now from within the controller's action, I get a warning:
Cannot find 'published_on=' for type 'Page'
If you put
class Page
include Mongoid::Document
include Mongoid::Timestamps
you get the rails automagic fields created_at and updated_at
So, I am having some issues with user authentication in embedded documents. I have two documents, one embedded in the other. A business has many members. The models look like this:
class Member
include Mongoid::Document
field :username, type: String
field :password, type: String
embedded_in :business
validates :username, :presence => true, :uniqueness => true, :length => 5..60
end
class Business
include Mongoid::Document
field :name, type: String
embeds_many :members
end
The problem is that it isn't validating the username's uniqueness in each model. When I save a member within a business, I can save a thousand of the same name. This of course is not going to work for a good authentication system. I am using Mongoid 2, Rails 3, and Ruby 1.9
This is a normal behavior when using embedded documents as explained here: MongoID validation
validates_uniqueness_of
Validate that the field is unique in the database: Note that for
embedded documents, this will only check that the field is unique
within the context of the parent document, not the entire database.
I think you want to try to create an Index in the username field that would ensure uniqueness among all the objects of that collection. Something like this:
ensureIndex({username:1},{unique:true});
EDIT: If you want Mongo to throw exception if a document with the same index value exists, you must avoid Mongo to do the “fire and forget” pattern. This means that the database will not wait for a response when you perform an update/write operation on a document.
And you want to pass this parameter: safe:true. By doing so Mongo should raise an exception if for any reason the document can't be inserted.