Gemfile:
gem 'http_accept_language'
config/initializers/locale.rb:
reference: tomafro.net
Sometimes you want to read just a single column from a collection of records, without the overhead of instantiating each and every one. You could just execute raw SQL, but it’s a shame to do away with the nice type conversion ActiveRecord provides. It’d also be a pity to get rid of find scoping, amongst other goodness.
module Tomafro::ColumnReader
def column_reader(column_name, options = {})
name = options.delete(:as) || column_name.to_s.pluralize
column = columns_hash[column_name.to_s]
You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
class Customer < ActiveRecord::Base
has_many :orders do
def find_by_order_prefix(order_number)
find_by(region_id: order_number[0..2])
end
end
# Association Callbacks | |
Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a :before_save callback to cause something to happen just before an object is saved. | |
Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks: | |
## avaliable callbacks | |
- before_add | |
- after_add |
# With this declaration, Rails will keep the cache value up to date, and then return that value in response to the size method. | |
# without contuer_cache option | |
# asking for the value of @customer.orders.size requires making a call to the database to perform a COUNT(*) query | |
# To avoid this call, you can add a counter cache to the belonging model: | |
belongs_to :customer, counter_cache: true | |
# throught association | |
class Physician < ActiveRecord::Base | |
has_many :appointments |
reference: ruby-journal.com
Install useragent gem by appending to Gemfile:
gem 'useragent'
The guide will assume that we are dealing with a pre-existing application that has two models: Album and Artist. An album belongs to an artist and an artist has many albums.
This guide is for Rails 4.0.0+ only.
These gems can always be replaced with alternatives, but they will be good for demonstration. Add the following gems to your Gemfile:
# /config/initializers/devise.rb | |
config.password_length = 8..128 | |
# user model validates | |
validate :password_complexity | |
def password_complexity | |
if password.present? and not password.match(/\A(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+\z/) | |
errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit" | |
end | |
end |