views:

72

answers:

1

I'm writing a quick app for a user to track their daily bills (for money tracking purposes). I want the user to be able to define their own categories that a bill can be applicable for. I'm trying however to decide the best way to model this and also validate categories as unique.

My initial thought was this:

class User
  include Mongoid::Document
  embeds_many :bills

  field :categories, :type => Array
end

class Bill
  include Mongoid::Document
  embeded_in :user, :inverse_of => :bills

  field :category
  index :category
end

So a user can add categories, just as strings, and when they add a bill, they'll choose from their available categories for the bill.

So, a couple questions:

  1. Does this seem like the proper design? I Don't think it's necessary to define an actual category model as it's literally just a string used to index bills on, but I'm not sure if there are other benefits to a separate model

  2. How do I validate_uniqueness_of :categories in my user model. I don't think it works on array items like this, but I could be wrong. I don't want a user to create categories with the same name. I suppose this might be the advantage of a separate model, embedded in the User, but again it seems like more work than necessary.

Can someone tell me my best options here to validate that a user has unique categories (but users can have the same categories, i obviously don't care about that, just unique in the scope of a single user)

A: 

[Update]

The design seems proper. In a Rails specific way how would you validate the uniqueness? When adding a category pull the list and do an indexOf check to ensure it doesn't exist. If it does just bounce back an error.

I'm not a Rails guy, let me know if I'm off track or something.


I'm not sure MongoDB would be the best choice of storage engines for that. You would be better off using MySQL with a categories table.

Knocks against MongoDB:

  • Not ACID transactions
  • No single server durability
  • Not relational (you want relational for a bill tracking application)
Josh K
this is more of an exercise for fun, i'm not writing an enterprise app or anything, i just wanted to learn mongo with rails3 and thought a quick little app like this would be a fun exercise
brad
@brad: I'm not a Rails guy, but I would be to store categories inline in an array under the user object. Let me update my answer.
Josh K
thanks for the answer, i should have mentioned that I obviously know how to do this manually with an `indexOf` or `include?`, just wasn't sure if there was a more railsy way to do this. I may end up selecting this answer though since it does technically answer my Q, will just wait a bit.
brad
@Brad: I mean pull the object and check if that object exists in Ruby not Mongo.
Josh K
ya i understand
brad