通过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"
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/
- 通过MongoMapper让程序在Rails 3.2上与MongoDB数据交互
- 通过 JNI 让 JAVA 与 Delphi 程序交互(五)
- Android学习笔记:在Android平台上通过JSON格式与服务器端进行数据交互
- Android学习笔记:在Android平台上通过JSON格式与服务器端进行数据交互
- ExtJS 与 Rails 数据交互 小记
- rails数据交互(1)
- rails数据交互(2)
- rails数据交互(3)
- rails数据交互(4)
- MongoDB 和 MongoMapper的示例用法简介
- 通过Ruboss让Flex与Rails完美结合
- 让Ruby On Rails抛在NginX + Mongrel上
- 通过ODBC与MySQL进行数据交互
- 通过AJAX与Servlet进行交互:通过JSON传递数据
- ajax与处理程序ashx数据交互
- mongodb 与 python3 交互
- mongoDB与Python交互
- 让java程序在linux上运行
- ORA-00600[kcratr_nab_less_than_odr]小记
- spring+dbcp的优化意见
- 回家后的一些感觉
- HibernateSessionFactoryUtil.java(Hibernate工具类)
- linux访问windows资源
- 通过MongoMapper让程序在Rails 3.2上与MongoDB数据交互
- 使用Visual Studio 2005 IDE的宏,自动为c#变量生成属性
- asp.Net中Gridview动态创建模板列
- 管理员必备的20个Linux系统监控工具
- 痛苦的面试...
- 如何手工移动PE头
- City Horizon
- VC异常处理
- 第三章:Android中资源的访问