I have been trying to validate that the first name does not include anything but letters, numbers, hyphens, or underscores.
In my users.rb model I am using this code:
validates :first_namename, :firstname_convention => true
Which goes to the FirstNameConvention class:
class FirstnameConventionValidator < ActiveModel::EachValidator
def validate_each(record, field, value)
unless value.blank?
record.errors[field] << "is not alphanumeric (letters, numbers, underscores or periods)" unless value =~ /^[[:alnum:]._-]+$/
record.errors[field] << "should start with a letter" unless value[0] =~ /[A-Za-z]/
record.errors[field] << "contains illegal characters" unless value.ascii_only?
end
end
end
And that file is stored in app/validators - a folder that I had to make.
I get this error:
ArgumentError in UsersController#index
Unknown validator: 'FirstnameConventionValidator'
I have tried placing:
config.autoload_paths += %W["#{config.root}/app/validators"]
In config/application.rb:
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ThorCinema
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.
# 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths << Rails.root.join('app', 'validators')
end
end
But this still doesn't work.
What am I doing wrong?
app/validators is a good place to store validators, all you need to do, is to tell Rails about this folder existence. Add this line to your autoload paths in config/application.rb (YourAppName::Application section):
config.autoload_paths << Rails.root.join('app', 'validators')
That's it
Related
Every time I call validates_with NumberValidator. I get an uninitialized constant error. I have created a directory called validators under the "app" directory. This is what I have so far.
This is my model
class Worker < ActiveRecord::Base
include ActiveModel::Validations
validates_with NumberValidator
end
This is my validator file
class NumberValidator < ActiveModel::Validator
def validate(record, attribute, value)
puts record
puts attribute
puts value
end
end
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ApplicationName
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.
# 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths += %W["#{config.root}/app/validators/"]
end
end
I have restarted my server and I'm just not sure what I am doing wrong
Rails will automatically load anything under app/ assuming you follow the expected structure. The way Rails does this is with Constant Autoloading, which maps a constant, such as MyValidator to a file name, such as my_validator.rb under a directory in the autoload paths.
In order for Rails to load your NumberValidator, you should name the file number_validator.rb and put it in a folder in the autoload path, such as app/validators/number_validator.rb. You will need to restart the server if you have added a directory under app because these are initialized at boot time (be sure to run spring stop if you are using spring so it restarts too!).
Notes:
You do not need to add anything under app to your app config, so you can remove the config.autoload_paths line.
ActiveRecord::Base already includes ActiveModel::Validations, so you can also remove that include from your Worker class.
For more information on how this process works, check out the Autoloading and Reloading Constants page in the Rails Guides.
I have a Rails app on Heroku and a separate WordPress blog hosted on GoDaddy. How can I route RailsApp.com/blog to the WordPress, while maintaining it as a subdirectory of the app?
For Rails3.1+ (+Rails4), you should follow these:
First, Add gem rack-proxy to Gemfile
gem "rack-proxy"
Then add file proxy.rb into Rails.root/lib like this:
require 'rack/proxy'
class Proxy < Rack::Proxy
def initialize(app)
#app = app
end
def call(env)
original_host = env["HTTP_HOST"]
rewrite_env(env)
if env["HTTP_HOST"] != original_host
perform_request(env)
else
# just regular
#app.call(env)
end
end
def rewrite_env(env)
request = Rack::Request.new(env)
if request.path =~ /^\/blog(\/.*)$/
# enable these code if you set blog as ROOT directory in wordpress folder
# env['REQUEST_PATH'] = '/'
# env['ORIGINAL_FULLPATH'] = '/'
# env['PATH_INFO'] = '/' # set root path request
env['REQUEST_URI'] = 'http://tinle1201.wordpressdomain.com' # your path
env["SERVER_PORT"] = 80
env["HTTP_HOST"] = "tinle1201.wordpressdomain.com" # point to your host
end
env
end
end*
Register proxy to middleware into config/application.rb:
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module AdultSavings
class Application < Rails::Application
config.autoload_paths += %W(#{config.root}/lib)
config.middleware.use "Proxy"
# 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.
# 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
end
end*
Add this line into php file wp-config.php:
define('WP_HOME', 'http://tinle1201.wordpressdomain.com/blog');
Rails configuration
Add to Gemfile:
gem "rack-reverse-proxy", :require => "rack/reverse_proxy"
Now we want /blog and /blog/ to be directed to the Wordpress instance from the Rails app.
Add this to your config.ru right before you run the app:
use Rack::ReverseProxy do
reverse_proxy(/^\/blog(\/.*)$/,
'http://CHANGEME.herokuapp.com$1',
opts = {:preserve_host => true})
end
In config/routes.rb add a route:
match "/blog" => redirect("/blog/")
I am a noob in Ruby/Rails and I am creating my first project now.
I am using Devise gem for authentication system. I have installed it and I am on fight to change the default messages from "en" (default language) to "pt-BR".
I have a file called devise.pt-BR.yml inside /config/locales/ with all translations for this language and I have followed a few tips but when I restart the server, I still get "en" as the default language.
I don't want to have two or more languages, I just need to work with "pt-BR" instead "en".
My environment:
Fedora 16
Ruby 1.9.2p320
Rails 3.2.6
Devise 2.1.2
/config/application.rb content (look at bottom):
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 Foo
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]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# 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.i18n.load_path += Dir[Rails.root.join('devise', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :"pt-BR"
I18n.locale = :"pt-BR"
end
end
Change the line
config.i18n.default_locale = :"pt-BR"
to
config.i18n.default_locale = "pt-BR"
I was wrong, it's working!
I had to drop it inside application.rb:
config.i18n.load_path += Dir[Rails.root.join('locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :'pt-BR'
And put "devise.pt-BR.yml" inside /config/locales/
I was looking for "Sign in" and label from fields at "Log in" view but I think these strings are not translatable, I will generate these views and manually revise them.
Thank you.
Try renaming your locale file to pt-BR.yml, or else change your reference in application.rb to devise.pt-BR.yml.
using devise 2.1.0
I had to override the devise registration controller. In the process I had to move my devise views directory to correspond with the new controller. I have this code in my config/applications.rb file
paths.app.views << "app/views/devise"
And it is throwing an error when I try and start my server with rails s:
...config/application.rb:65:in `<class:Application>': undefined method `app' for #<Rails::Paths::Root:0x00000103537740> (NoMethodError)
I am relatively new at rails. But I get that there is a root class somewhere that didn't define app. I got this advice to use this paths.app.views here at stack.
Here is the full applications.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 Growle
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, :password_confirmation]
#don't generate RSpec tests for views and helper
config.generators do |g|
g.view_specs false
g.helper_specs false
end
# 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'
paths.app.views << "app/views/devise"
end
end
By reading the last comment of yours, it sound that you want either view_paths= or prepend_view_path.
Those can be set at class level in your controller.
If that isn't what you are looking for, consider reading Override devise registrations controller for information.
I have a rails 3 app, and am trying to do testing. I do the following command rspec spec/controllers/ and get the following error:
/config/application.rb:42:in `<<': can't modify frozen array (TypeError)
from c:/Users/#####/documents/#####/config/application.rb:42
It is pointing to my config/application.rb file which I have provided below.
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module PadOnRails
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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# 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]
config.autoload_paths << "#{config.root}/lib"
end
end
has anyone else experienced this exact kind of problem. If so how do you fix it because I have deleted my project and did a git clone all over and still get the same error.
Try the method the comments suggest:
config.autoload_paths += %W{#{config.root}/lib}
This doesn't modify the initial array, but adds the given array to config.autoload_paths and saves it into a new array in config.autoload_paths.