Rails extending ActiveRecord::Base

There are several approaches : Using ActiveSupport::Concern (Preferred) Read the ActiveSupport::Concern documentation for more details. Create a file called active_record_extension.rb in the lib directory. require ‘active_support/concern’ module ActiveRecordExtension extend ActiveSupport::Concern # add your instance methods here def foo “foo” end # add your static(class) methods here class_methods do #E.g: Order.top_ten def top_ten limit(10) end end … Read more

Best way to create unique token in Rails?

— Update — As of January 9th, 2015. the solution is now implemented in Rails 5 ActiveRecord’s secure token implementation. — Rails 4 & 3 — Just for future reference, creating safe random token and ensuring it’s uniqueness for the model (when using Ruby 1.9 and ActiveRecord): class ModelName < ActiveRecord::Base before_create :generate_token protected def … Read more

Can you get DB username, pw, database name in Rails?

From within rails you can create a configuration object and obtain the necessary information from it: config = Rails.configuration.database_configuration host = config[Rails.env][“host”] database = config[Rails.env][“database”] username = config[Rails.env][“username”] password = config[Rails.env][“password”] See the documentation for Rails::Configuration for details. This just uses YAML::load to load the configuration from the database configuration file (database.yml) which you can … Read more

How to run a single test from a Rails test suite?

NOTE: This doesn’t run the test via rake. So any code you have in Rakefile will NOT get executed. To run a single test, use the following command from your rails project’s main directory: ruby -I test test/unit/my_model_test.rb -n test_name This runs a single test named “name”, defined in the MyModelTest class in the specified … Read more