2012-02-17 3 views
0

Я использую mysql в новом приложении rails, но теперь я хотел дать mongoDB попробовать, поэтому я установил mongo mapper и mongoid (чтобы использовать сеанс mongo). Установка кажется прекрасной, потому что я могу создавать монго-модели. Но по какой-то причине rails все еще пытается подключиться к mysql: Can't connect to local MySQL server.Почему рельсы пытаются подключиться к mysql?

Это ужасно, потому что даже если я не использовал монго, рельсы не должны пытаться подключаться к mysql для каждого запроса. Это бросает эту ошибку даже на несуществующие URL-адреса.

Что делать, чтобы отладить это? Думаю, я мог бы попробовать удалить gem-файл mysql из Gemfile и запустить bundle install. Но мне все еще не нравится тот факт, что он пытается подключиться, даже когда я его не использую. Не следует ли пытаться соединить «лениво» (т. Е. Только по требованию)?

development.rb:

Myapp::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 = true 
end 

application.rb:

require File.expand_path('../boot', __FILE__) 

require 'rails/all' 

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) 
end 

module Myapp 
    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' 

config.generators do |g| 
    g.orm :mongo_mapper 
end 
    end 
end 
+0

показать нам свою конфигурацию – Joe

ответ

3

Когда ActiveRecord является частью приложения, он пытается установить соединение с базой данных при запуске. Если соединение невозможно, приложение не запускается.

Проблема здесь:

require 'rails/all' 

Эта линия включает в себя все "обычные" рельсы компоненты, ActiveRecord среди них. Если вы идете к его определению, оно должно выглядеть следующим образом (для рельсов 3.2):

require "rails" 

%w(
    active_record 
    action_controller 
    action_mailer 
    active_resource 
    rails/test_unit 
    sprockets 
).each do |framework| 
    begin 
    require "#{framework}/railtie" 
    rescue LoadError 
    end 
end 

Возьмите этот код, удалите active_record линию и поставить его вместо того, чтобы ваш rails/all линию. Теперь, ActiveRecord не входит и ваша заявка будет громко не в состоянии, когда он видит ссылки ActiveRecord в коде, например:

config.active_record.mass_assignment_sanitizer = :strict 

Вы должны удалить их тоже. Вам не нужно удалять database.yml, но вы, вероятно, должны, так как теперь он не имеет никакого значения.

+0

Читателям: это ответ, хотя я не знаю, работает ли код, потому что я просто переустановил приложение с -skip-active-record (которое сгенерировало нечто похожее на код выше) , Но мне все же хотелось бы знать, в чем причина активной записи для автоматического подключения к mysql, даже если я не использую его в конкретном запросе, который кажется отсталым. Я новичок в рубинах и рельсах, и я до сих пор не знаю их внутренних дел. – HappyDeveloper

+0

@HappyDeveloper: в ActiveRecord нет «ленивого подключения». Он соединяется во время инициализации. Вот как это работает. Монгоид делает то же самое. Не знаю о MongoMapper. –

0

Вам нужно удалить строку, где настроить ActiveRecord:

# 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 
+1

Это не решило проблему. В любом случае, почему? Почему рельсы пытаются подключиться к mysql для любого запроса? – HappyDeveloper

+0

с auto_explain a предположим – shingara

0

я полагаю, вы проверили ваш database.yml, чтобы убедиться, что ничего не ищет adapter: mysql?

Также, если вы оставили mysql в своем Gemfile, тогда gem mysql будет бомбить, поскольку он не может сделать это, и поэтому должен терпеть неудачу как зависимость. Удалите его + повторите.