Question

I am a newer in rails development. When using mongoid in rails4, I don't know how to make the model I build mapped as a table in my local mongodb.

Here is user.rb:

class User

  include Mongoid::Document
  include Mongoid::Timestamps

  field :username, type: String
  field :email, type: String
  field :role, type: String
  field :password, type: String

  validates_presence_of :username, :password
  validates_uniqueness_of :username
  validates_inclusion_of :role, in: %w(guest admin)

  class << self
    def authenticate(username, password)
      user = find_by(username: username, password: password)
      if user
        user
      end
    end
  end
end

According to the rails start guide. We can use rails generate model User, and then rake db:migrate to create a model in table. But when I use mongodb as database, I'm confused.

Now database have configured successfully, that means my local environment has the database I configured. But the user table doesn't exist, I just want to know how to make the model mapped to table in database. Do I have to create it with some command or just need to load the model in somewhere. Many thanks to you guys of answer this question.

Was it helpful?

Solution

For MongoDB you don't need migrations, because it's schema less. Just store a record and it will appear in your database.

And because it IS schema less, you can change your Rails model, without migrating your database, MongoDB won't bother. But be sure, that your application can handle both versions of your stored stuff.

But if you want, you CAN write migrations, that transform your old data, into your new schema, when you have changed something in your Rails models (but I would start writing migrations not before I have some production data, for development it's ok to drop the DB and recreate it). But as I said, that only bothers your Rails application. MongoDB allows you to do everything without migrations.

OTHER TIPS

Take care of following things.

  1. Skip Active record while generating rails application with mongoDB.

    • rails new app_name --skip-active-record
  2. Open config/application.rb and near the top, remove the line require "rails/all" and add the following lines so you end up with this

    • require "action_controller/railtie"
    • require "action_mailer/railtie"
    • require "active_resource/railtie"
    • require "rails/test_unit/railtie"
  3. Rails 3.2+ you'll also need to remove configuration options for Active Record that reside in your environments, config/environments/development.rb

    • # config.active_record.mass_assignment_sanitizer = :strict
    • # config.active_record.auto_explain_threshold_in_seconds = 0.5
  4. Rails 3.2.3+ you'll also need to comment out the following line in config/application.rb

    • # config.active_record.whitelist_attributes = true

To design rails application with mongoDB is like Fun!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top