同时要确保generate命令,不要去对对象关联active_record的orm
# Configure generators values. Many other options are available, be sure to check the documentation.
# config.generators do |g|
# g.orm :active_record
# g.template_engine :erb
# g.test_framework :test_unit, :fixture => true
# end
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "project_name_#{Rails.env}"
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
MongoMapper.connection.connect if forked
end
end
测试配置
创建文件 lib/tasks/mongo.rake 添加内容:
namespace :db do
namespace :test do
task :prepare do
# Stub out for MongoDB
end
end
end
--------------------------------------------------------------------
中间遇到的问题以及解决过程
问题一、运行rails s ,出现错误提示:
**Notice: C extension not loaded. This is required for optimum MongoDB Ruby driver performance.
You can install the extension as follows:
gem install bson_ext
If you continue to receive this message after installing, make sure that the
bson_ext gem is in your load path and that the bson_ext and mongo gems are of the same version.
gems/ruby-1.9.2-p180/gems/execjs-1.3.0/lib/execjs/runtimes.rb:50:in `autodetect': Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
from /home/chinacheng/.rvm/gems/ruby-1.9.2-p180/gems/execjs-1.3.0/lib/execjs.rb:5:in `<module:ExecJS>'
from /home/chinacheng/.rvm/gems/ruby-1.9.2-p180/gems/execjs-1.3.0/lib/execjs.rb:4:in `<top (required)>'
提示缺少gem包 gem install bson_ext
安装之后,再运行,仍然出现上面这个错误
在Gemfile中添加
gem "bson_ext"
执行rails s
**Notice: C extension not loaded 这个问题就不存在了
还剩下JavaScript runtime这个错误,查了一下原因是:
Windows下默认有Javascript引擎,所以window下不会有这个错误。Linux下才有这个错误,一般只要第一个项目安装即可,以后的项目不用重复安装。
而且这个错误是由development环境中的assets包引起的,注释掉
# Gems used only for assets and not required
# in production environments by default.
#group :assets do
# gem 'sass-rails', " ~> 3.1.0"
# gem 'coffee-rails', "~> 3.1.0"
# gem 'uglifier'
#end
就不用安装’execjs’和’therubyracer’了。
当然这不是一个好办法
如果不注释,需要在Gemfile中添加
同理在1.9中没问题,1.8中要改成:key=>'_project_name_session'
上面这个问题突出的问题是:ruby1.8于ruby1.9在hash定义上出现的变化
#新的语法
h = { a: 1, b: 2 }#
#旧的语法
h = { :a=> 1, :b=>2 }# 返回{:a=>1, :b=>2}
1.9.2同时兼容以前1.8.7的写法
----------------------------------------------------------------------------
接下来继续做那个demo 首先做一下首页的显示
运行指令
rails g controller index
创建index的控制器以及其他代码
先写测试
在控制器的测试文件中添加
require 'test_helper'
class IndexControllerTest < ActionController::TestCase
test "access the index page" do
get :index
assert_response 200
end
end
class UserTest < ActiveSupport::TestCase
test "new user test" do
assert_equal User.count,0
assert_difference "User.count",1 do
User.create(:name=>"王华",:age=>18)
end
user = User.last
assert_equal user.name, "王华"
assert_equal user.age, 18
end