Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Thursday, April 3, 2014

Dropping a database after running rspec tests with MongoMapper or Mongoid

The mongodb folder on my development computer was using 11 gb, and I needed to free up some space on /var, since that was on the / partition. (Yes, it is recommended to have it on separate partition, but that is another discussion).

In your rspec add this:

RSpec.configure do |config|
  config.after(:suite) do
    # for MongoMapper
    db = MongoMapper.database
    # for Mongoid
    # db = Mongoid.master
    # drop the database
    db.command({dropDatabase:1})
  end
end


For using mongo directly, you need to access the db object and trigger the command as above.

Monday, October 14, 2013

Get the dot notation of a embedded Mongoid element

I needed to get the dot notation for embedded documents to perform queries using the given dot notation.

I could not find a "standard" way of doing just that, so here are some helper methods I use in a class. (Part of soon-to-come BoxCMS)

This Gist uses Mongoid metadata and reflect_on_all_associations, so it might break for newer versions of mongoid at some point.

Using dot notation queries in mongoid, makes it easy to dig for even the deepest "weird" embedded structures you might have.

Example of query:
»  Box::Page.where("rows.boxes.box_items.is_template_object" => false).first

Dot notations in mongodb are a powerful tool, but use it wisely unless you are indexing "more than you should".
Basic usage: Call dot_notation_for_element(embedded_element) to get the dot notation all the way up to the parent document, excluding the parent documents name/embedded name.

Thursday, October 25, 2012

Rails 3.2 and virtual attributes

I was fighting with virtual attributes for a few hours, and I'll share what I did wrong:

Here's a model with one virtual attribute as well as a text field

class User < ActiveRecord::Base
  attr_accessible :sanity_level
  attr_accessor   :sanity_level

  validates_presence_of :sanity_level, :on => :update
end

I would expect the following to work:

user = User.create(:name => "Leif")
user.save(:sanity_level => 5)
user.valid?
# => false # What?
user.errors.inspect
# => Errors show: Sanity Level cannot be blank... but it is 5?
user.update_attributes(:sanity_level => 5)
user.valid?
# => true

I expected both to work, but it doesn't by design. After looking at activerecord and mysql2 source, it is easly spotted that save calls create_or_update without forwarding the hash, so of course it will fail!
To summarize and remember for the future:
  1. Use update_attributes when updating with a hash for the attributes to update
  2. Use save after setting attributes manually
  3. Use create when creating new records
  4. Use build when building new records with a hash and saving later
And a note to myself again: Don't use save when updating attributes.