Rails with Mongo Mapper - ruby-on-rails

This is turning out to be the worst day for learning rails. Already failed to connect and configure to sqlite3, mysql databases I turned to mongo mapper and facing the same issues. When I try to start the rails server I get the following:
/usr/local/lib/ruby/gems/1.8/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `require': no such file to load -- mongo_mapper (LoadError)
I have already installed mongo_mapper gem but when I do 'which mongo_mapper' it does not return anything.
Here is my mongo_config.rb file placed inside the initializers folder:
require "rubygems"
require "mongo_mapper"
MongoMapper.database = "blog-#{Rails.env}"
UPDATE 1:
I changed to the following:
require "rubygems"
include MongoMapper
MongoMapper.database = "blog-#{Rails.env}"
And now I get the following error:
/Users/azamsharp/Projects/railsprojects/blog/config/initializers/mongo_config.rb:2: uninitialized constant MongoMapper (NameError)

You must use bundler with rails 3. don't try to not use it. add the following to your Gemfile
source 'http://gemcutter.org'
source 'http://rubygems.org'
gem "rails", "3.0.7"
gem 'bson', "1.1.1"
gem 'bson_ext', "1.1.1"
gem 'mongo_mapper'
then run
bundle install
then rails server will work

In order to get mongo_mapper working in Rails (tested under Rails 3.1, should work in Rails 3.0.x as well), you have to follow these steps:
In Gemfile, add the mongo_mapper and bson gem:
gem 'mongo_mapper'
gem 'bson_ext'
Run bundle install
In the config/ directory, create a mongo.yml file like this one:
# config/mongo.yml
defaults: &defaults
host: 127.0.0.1
port: 27017
development:
<<: *defaults
database: db_development
username: user
password: password
test:
<<: *defaults
database: db_test
# set these environment variables on your prod server
production:
<<: *defaults
database:
username:
password:
In the config/initializers directory, create a mongo.rb file like this:
# config/initializers/mongo.rb
#include MongoMapper
db_config = YAML::load(File.read(File.join(Rails.root, "/config/mongo.yml")))
#
if db_config[Rails.env] && db_config[Rails.env]['adapter'] == 'mongodb'
mongo = db_config[Rails.env]
MongoMapper.connection = Mongo::Connection.new(mongo['host'] || 'localhost',
mongo['port'] || 27017,
:logger => Rails.logger)
MongoMapper.database = mongo['database']
if mongo['username'] && mongo['password']
MongoMapper.database.authenticate(mongo['username'], mongo['password'])
end
end
# Used for image uploads
# CarrierWave.configure do |config|
# mongo = db_config[Rails.env]
# config.grid_fs_database = mongo['database']
# config.grid_fs_host = mongo['host'] || 'localhost'
# config.grid_fs_access_url = "gridfs"
# config.grid_fs_username = mongo['username']
# config.grid_fs_password = mongo['password']
# end
# It's also possible to define indexes in the the model itself; however,
# a few issues are being worked out still. This is a temporary solution.
# Comment.ensure_index([["story_id", 1], ["path", 1], ["points", -1]])
# MongoMapper.ensure_indexes!
# Handle passenger forking.
# if defined?(PhusionPassenger)
# PhusionPassenger.on_event(:starting_worker_process) do |forked|
# MongoMapper.database.connect_to_master if forked
# end
# end
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
MongoMapper.connection.connect if forked
end
end
Start the mongod server before starting the rails server and enjoy!

Try removing the require lines and replace them with include MongoMapper

Related

undefined method `each' for #<String:0x00000003a27a58>

First, I do really apologize, since I'm still newbie on this.
I was trying to install Fat Free CRM by following the instruction on this following sites:
http://www.blogdugeek.fr/crm-installation-fat-free-crm-debian-squeeze/
http://guides.fatfreecrm.com/Setup-Linux-or-Mac-OS.html
As I follow the instructions, I've encounter some errors and resolved some. However, upon executing this command:
RAILS_ENV=production rake db:create db:migrate crm:settings:load
I was stuck in this command line and here are the following errors that I've been stuck with:
rake aborted!
NoMethodError: undefined method `each' for #<String:0x00000003a27a58>
/usr/local/rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/connection_adapters/connection_specification.rb:150:in `resolve_all'
/usr/local/rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/connection_handling.rb:69:in `resolve'
/usr/local/rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/core.rb:46:in `configurations='
/usr/local/rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/railties/databases.rake:5:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => db:create => db:load_config
(See full trace by running task with --trace)
As I've search for more related issue, I found some, but it's still no use.
Also, here are some data that might be needed:
Ruby Version
ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-linux]
Rails Version
Rails 4.2.6
Here are the error lines
connection_specification.rb
def resolve(config)
if config
resolve_connection config
elsif env = ActiveRecord::ConnectionHandling::RAILS_ENV.call
resolve_symbol_connection env.to_sym
else
raise AdapterNotSpecified
end
end
# Expands each key in #configurations hash into fully resolved hash
def resolve_all
config = configurations.dup
config.each do |key, value| <---- Error line
config[key] = resolve(value) if value
end
config
end
connection_handling.rb
class MergeAndResolveDefaultUrlConfig # :nodoc:
def initialize(raw_configurations)
#raw_config = raw_configurations.dup
#env = DEFAULT_ENV.call.to_s
end
# Returns fully resolved connection hashes.
# Merges connection information from `ENV['DATABASE_URL']` if available.
def resolve
Error line ----> ConnectionAdapters::ConnectionSpecification::Resolver.new(config).resolve_all
end
private
def config
#raw_config.dup.tap do |cfg|
if url = ENV['DATABASE_URL']
cfg[#env] ||= {}
cfg[#env]["url"] ||= url
end
end
end
core.rb
def self.configurations=(config)
Error line ---> ##configurations = ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig.new(config).resolve
end
self.configurations = {}
# Returns fully resolved configurations hash
def self.configurations
##configurations
end
databases.rake
db_namespace = namespace :db do task :load_config do
Error line ----> ActiveRecord::Base.configurations = ActiveRecord::Tasks::DatabaseTasks.database_configuration || {}
ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths
Here's the config/database.yml file.
# MySQL. Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
# gem install mysql2
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
#------------------------------------------------------------------------------
development:&development
adapter:mysql2
encoding:utf8
database:fat_free_crm_development
pool:5
username:root
# password:
socket:/var/run/mysqld/mysqld.sock
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *development
database: fat_free_crm_test
production:
adapter: mysql
encoding: utf8
database: fat_free_crm_production
pool: 5
username: root
password:
socket: /var/run/mysqld/mysqld.sock
socket: /tmp/mysql.sock
staging:
<<: *development
database: fat_free_crm_staging
Hope to hear and seek some advises and learning.
If there's need some more information, let me know.
Thanks,
Your database.yml is the problem. YAML requires a separator between the key and data.
So not like this:
production:
adapter:mysql
encoding:utf8
...
But like this:
production:
adapter: mysql
encoding: utf8
...
You need to correct all the lines in the file, because you have this error everywhere.
Check the database.yml file again. Don't add anything
ie the file format must be correct.
had unkowngly comment a line on to that was causing the error.

How can I use the methods in ActiveRecord::ConnectionAdapters::SchemaStatements in isolation?

I am writing a script which I can write in postgresql but would like to write using ActiveRecord. Most of the methods that I would like to use are located in ActiveRecord::ConnectionAdapters::SchemaStatements. Because this is a module how can I use these methods in an ActiveRecord::Base.transaction block. I've already tried calling the methods directly like so:
ActiveRecord::ConnectionAdapters::SchemStatements.drop_table etc.
This doesn't seem to work. Is it even possible to use ActiveRecord like this?
You need to require active_record, establish a connection to the database and then you can use all the methods through the connection method:
# test.rb
require 'active_record'
require 'pg'
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
database: 'database',
username: 'username',
password: 'passwd'
)
puts ActiveRecord::Base.connection.table_exists?('users')
Test run (when the users table indeed exists in my database):
$ ruby test.rb
true
I recently had to do the exact same thing, and, yes, this is possible. I started with a regular Rails project (rails new app) and stripped it down to fit my needs.
My final project structure has only the following folders and files (everything else was deleted):
/app/models/*
/bin/bundle
/bin/rake
/bin/spring
/config/application.rb
/config/boot.rb
/config/database.yml
/config/environment.rb
/config/environments/*
/db/schema.rb
/config.ru
/Gemfile
/Gemfile.lock
/Rakefile
My Gemfile contains:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '< 5.0.0'
# Use mysql as the database for Active Record
gem 'mysql2' # <-- change this to PostgreSQL
I also have a script app.rb, which I placed at the root of the project:
# ensure that all dependent gems are installed before running
require_relative 'config/boot'
# include dependent libraries
require 'active_record'
require 'active_model'
require 'mysql2' # <-- change this to PostgreSQL
require 'yaml'
# set up environment and connect to the database
environment = ENV['RAILS_ENV'] || 'development'
database = YAML.load_file('config/database.yml')
ActiveRecord::Base.establish_connection database[environment]
# set up logging so you can use $logger.debug or $logger.info anywhere in your code
$logger = Logger.new(File.new("log/#{environment}.log", 'w'))
$logger.level = environment == 'development' ? Logger::DEBUG : Logger::INFO
# include dependent classes in same directory
# this step is optional as the required files can be included as needed
Dir['app/models/*.rb'].each { |file| require_relative file }
Now, suppose you have a model called User defined in /app/models/user.rb as
class User < ActiveRecord::Base
end
You can then write statements like the one below in any file that is included from app.rb:
#execute code as a single transaction
ActiveRecord::Base.transaction do
user1 = User.create!(first_name: 'Richard', last_name: 'Rahl')
user2 = User.create!(first_name: 'Kahlan', last_name: 'Amnell')
end
You can even use statements like has_many, belongs_to, etc in your models without any problems.
Hopefully, this will be enough to get you started. Let me know if you need more details.

How to configure ActiveRecord database connection with mysql2 gem

Hey everyone Having an issue using ActiveRecord with the 'mysql2' gem. I'm using rails 4.0.4 There are these lines in my config/application.rb
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
when i try to run 'rails g model user' i get
invoke active_record
/Users/edjasper/.rvm/gems/ruby-2.1.1/gems/railties4.0.4/lib/rails/application/configuration.rb:110:in `database_configuration': Could not load database configuration. No such file - /Users/edjasper/Desktop/associations_challenge_8/config/database.yml (RuntimeError
any advice?
yes, you don't have database.yml in config dir
smth like
development:
adapter: mysql2
encoding: utf8
database: my_db_name
username: root
password: my_password
host: 127.0.0.1
port: 3306
secure_auth: false
also you should already have database.yml.example in your config dir for sample
by the way error message already told you about it :)
No such file - /Users/edjasper/Desktop/associations_challenge_8/config/database.yml

ActionView::Template::Error (db_name must be a string or symbol):

Ok so i have a new rails app that i have on ubuntu 11.10 on ec2 and it has mongoid as the db and i keep getting this error
ActionView::Template::Error (db_name must be a string or symbol):
Here is my config/mongoid.yml
development:
host: localhost
database: mm_development
test:
host: localhost
database: mm_test
# set these environment variables on your prod server
production:
host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
# - host: slave1.local
# port: 27018
# - host: slave2.local
# port: 27019
and my database.yml is blank because i didnt know what if anything needs to go there. Here is my gemfile for mongoid
gem 'rails', '3.2.3'
gem 'jquery-rails'
gem 'haml'
gem 'unicorn'
gem 'mongoid'
First i want to know if anyone know what i need to do with database.yml and then how do i solve this issue....mongo is up and running but this error is confusing
If you want to run with blank config/database.yml or remove it, you must remove all references to Active Record. The following worked for me, check it for config/application.rb and what I had to do to get a fresh Rails project to pass an initial test with your supplied Gemfile and config/mongoid.yml. Note that you also should comment out "fixtures :all" in test/test_helper.rb. I recommend that you recreate your equivalent of the following as a clean base from which to start. Hope that this helps.
$ ruby -v
ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin11.3.0]
$ rails _3.2.3_ new free-11137-db_name
$ cd free-11137-db_name
Gemfile as per user
$ bundle install
$ gem install unicorn
$ bundle install
Using mongo (1.6.2)
Using mongoid (2.4.8)
$ rails g mongoid:config
config/mongoid.yml as per user
config/database.yml blank as per user
config/application.rb
#require 'rails/all'
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
# require "sprockets/railtie" # Uncomment this line for Rails 3.1+
remove all references to Active Record as follows
config/application.rb
#config.active_record.whitelist_attributes = true
config/environments/development.rb
#config.active_record.mass_assignment_sanitizer = :strict
#config.active_record.auto_explain_threshold_in_seconds = 0.5
config/environments/test.rb
#config.active_record.mass_assignment_sanitizer = :strict
test/test_helper.rb
#fixtures :all
$ rails g model person
$ cat app/models/person.rb
class Person
include Mongoid::Document
end
$ rm test/fixtures/people.yml
$ bundle exec rake test # succeeds
$ rm config/database.yml
$ bundle exec rake test # succeeds

rails and mongodb

I am trying out mongodb with Rails 3. after following instructions from mongomapper's site and a few others, i haven't been able to solve one small issue...
No value provided for required options '--orm'
I added a file mongo.rb in my config folder to make stuff tick
MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "cobboc_#{Rails.env}"
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
MongoMapper.connection.connect if forked
end
end
The mongo.rb file should be in config/initializers and contain:
require 'mongo_mapper' # loading mongo_mapper
MongoMapper.connection = Monog::Connection.new # localhost and port 27017 are the default values
MongoMapper.database = "cobboc_#{Rails.env}"
The Passenger extension is already done in the MongoMapper code.
If you'd like to use the database.yml file for configuration you can do:
require 'mongo_mapper'
db_config = YAML::load(File.read("#{Rails.root}/config/database.yml"))
if db_config[Rails.env] && db_config[Rails.env]['adapter'] == 'mongodb'
mongo_config = db_config[Rails.env]
MongoMapper.connection = Mongo::Connection.new(mongo_config['host'])
MongoMapper.database = mongo_config['database']
end
The project rails3-generators provides MongoMapper model generators to solve your issue. Require the gem in your Gemfile.
# Gemfile
gem 'rails3-generators'
Note, the Rails 3 generators have moved to the mongo_mapper gem
You didn't specify where you were getting the "orm" error
If it was in the "generate model" case you could call the following:
sudo gem install rails3-generators
rails generate model Book --skip-migration --orm=mongomapper
I was running:
$ rails generate scaffold project name:string
>> No value provided for required options '--orm'
Solution:
Add rails3-generators to Gemfile
$ rails g scaffold project name:string --skip-migration --orm=mongomapper

Resources