通过MongoMapper让程序在Rails 3.2上与MongoDB数据交互

来源:互联网 发布:安装补丁的软件 编辑:程序博客网 时间:2024/05/16 11:47

参考资料:http://www.mongodb.org/display/DOCS/Rails+3+-+Getting+Started

http://mongomapper.com/documentation/getting-started/rails.html

如果是建立新工程项目,使用:

rails new my_app --skip-active-record

来屏蔽ActiveRecord组件。如果程序已经建立起来了, 可以修改config/application.rb文件:

替换:

require 'rails/all'

为:

require "action_controller/railtie"

require "action_mailer/railtie"

require "active_resource/railtie"

require "rails/test_unit/railtie"

# Uncomment for asset pipelining in Rails 3.1

# require "sprockets/railtie"

config/application.rb中还可加入如下代码:

module xxxxxx
  class Application < Rails::Application

    ......

    # allow to use the rails generate model command with MongoMapper
    config.generators do |g|
      g.orm :mongo_mapper
    end

  end
end

修改好的config/application.rb文件大致如下:

require File.expand_path('../boot', __FILE__)#require 'rails/all'require "action_controller/railtie"require "action_mailer/railtie"require "active_resource/railtie"require "rails/test_unit/railtie"if defined?(Bundler)  # If you precompile assets before deploying to production, use this line  Bundler.require(*Rails.groups(:assets => %w(development test)))  # If you want your assets lazily compiled in production, use this line  # Bundler.require(:default, :assets, Rails.env)endmodule MongoRoR  class Application < Rails::Application    # Settings in config/environments/* take precedence over those specified here.    # Application configuration should go into files in config/initializers    # -- all .rb files in that directory are automatically loaded.    # Custom directories with classes and modules you want to be autoloadable.    # config.autoload_paths += %W(#{config.root}/extras)    # Only load the plugins named here, in the order given (default is alphabetical).    # :all can be used as a placeholder for all plugins not explicitly named.    # config.plugins = [ :exception_notification, :ssl_requirement, :all ]    # Activate observers that should always be running.    # config.active_record.observers = :cacher, :garbage_collector, :forum_observer    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.    # config.time_zone = 'Central Time (US & Canada)'    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]    # config.i18n.default_locale = :de    # Configure the default encoding used in templates for Ruby 1.9.    config.encoding = "utf-8"    # Configure sensitive parameters which will be filtered from the log file.    config.filter_parameters += [:password]    # Use SQL instead of Active Record's schema dumper when creating the database.    # This is necessary if your schema can't be completely dumped by the schema dumper,    # like if you have constraints or database-specific column types    # config.active_record.schema_format = :sql    # Enforce whitelist mode for mass assignment.    # This will create an empty whitelist of attributes available for mass-assignment for all models    # in your app. As such, your models will need to explicitly whitelist or blacklist accessible    # parameters by using an attr_accessible or attr_protected declaration.    # config.active_record.whitelist_attributes = true    # Enable the asset pipeline    config.assets.enabled = true    # Version of your assets, change this if you want to expire all your assets    config.assets.version = '1.0'        # allow to use the rails generate model command with MongoMapper    config.generators do |g|      g.orm :mongo_mapper    end  endend
修改Gemfile文件如下:

source 'https://rubygems.org'gem 'rails', '3.2.1'gem 'mongo_mapper'gem 'bson_ext'# Bundle edge Rails instead:# gem 'rails', :git => 'git://github.com/rails/rails.git'#gem 'sqlite3'# Gems used only for assets and not required# in production environments by default.group :assets do  gem 'sass-rails',   '~> 3.2.3'  gem 'coffee-rails', '~> 3.2.1'  # See https://github.com/sstephenson/execjs#readme for more supported runtimes  # gem 'therubyracer'  gem 'uglifier', '>= 1.0.3'endgem 'jquery-rails'# To use ActiveModel has_secure_password# gem 'bcrypt-ruby', '~> 3.0.0'# To use Jbuilder templates for JSON# gem 'jbuilder'# Use unicorn as the web server# gem 'unicorn'# Deploy with Capistrano# gem 'capistrano'# To use debugger# gem 'ruby-debug19', :require => 'ruby-debug'
运行bundle

bundle install
运行如下指令来生成config/mongo.yml文件

script/rails generate mongo_mapper:config

新建config/initializers/mongo.rb文件:

#MongoMapper.connection = Mongo::Connection.new('localhost', 27017)#MongoMapper.database = "#myapp-#{Rails.env}"#MongoMapper.database = ""if defined?(PhusionPassenger)   PhusionPassenger.on_event(:starting_worker_process) do |forked|     MongoMapper.connection.connect if forked   endend

新建lib/tasks/mongo.rake文件:

namespace :db do  namespace :test do    task :prepare do      # Stub out for MongoDB    end  endend
运行测试:

rake test:units --trace

新建Models:user.rb和hobby.rb


class User  include MongoMapper::Document  key :name, String  key :age, Integer  many :hobbiesend

class Hobby  include MongoMapper::EmbeddedDocument  key :name, String  key :time, Timeend
给工程添加一个测试用的controller, 运行指令如下:

rails generate controller home index

修改代码:

class HomeController < ApplicationController  def index    user = User.new(:name => 'Brandon')    user.hobbies.build(:name => 'Programming', :time => 10.years.ago)    user.save!#    @users = User.all    @user = User.where(:name => 'Brandon').first  endend
<h1>Home#index</h1><p>Find me in app/views/home/index.html.erb</p><br><%= @user.name %>
<br><%= @user.hobbies[0].time %>

还可以修改route.rb文件来修改主页

  get "home/index"  root :to => "home#index"

删除public下index.htm

在启动server前,还需要注释掉各个环境文件中的对activerecord的引用,例如,现在是开发环境:

打开:config/environments/development.rb,修改后大致如下:

MongoRoR::Application.configure do  # Settings specified here will take precedence over those in config/application.rb  # In the development environment your application's code is reloaded on  # every request. This slows down response time but is perfect for development  # since you don't have to restart the web server when you make code changes.  config.cache_classes = false  # Log error messages when you accidentally call methods on nil.  config.whiny_nils = true  # Show full error reports and disable caching  config.consider_all_requests_local       = true  config.action_controller.perform_caching = false  # Don't care if the mailer can't send  config.action_mailer.raise_delivery_errors = false  # Print deprecation notices to the Rails logger  config.active_support.deprecation = :log  # Only use best-standards-support built into browsers  config.action_dispatch.best_standards_support = :builtin    #好像这个是可以留着的  # Raise exception on mass assignment protection for Active Record models#  config.active_record.mass_assignment_sanitizer = :strict  # Log the query plan for queries taking more than this (works  # with SQLite, MySQL, and PostgreSQL)#  config.active_record.auto_explain_threshold_in_seconds = 0.5  # Do not compress assets  config.assets.compress = false  # Expands the lines which load the assets  config.assets.debug = trueend

启动server:

rails server

参考资料:http://mongomapper.com/

原创粉丝点击