Liskov Substitution Principle. Formally, this states, “Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T.”
- load, require https://prograils.com/posts/ruby-methods-differences-load-require-include-extend require reads and parses files only once, when they were referenced for the first time. load reads and parses files every time you call `load`.
- include, extend
include , add methods to class
extend , Unlike include, which adds module’s methods as instance methods, extend allows you to add them as a class methods.
module TestModule def some_method "Some method of #{self.class}" end end class TestClass1 extend TestModule # ... end class TestClass extend TestModule # ... end TestClass2.some_method TestClass1.new.some_method
*install gem globally rvm @global do gem install [gem_name] to install gem globally (per ruby version). It is not possible to install gem globally for every ruby version. According to https://rvm.io/gemsets/initial you can define automatically installed gems for every ruby version in file ~/.rvm/gemsets/global.gems. In this file you need to define required gems (one per line) e.g. bundler zeus
- integer
:limit NumericType ColumnSize Maxvalue 1 tinyint 1 byte 127 2 smallint 2 bytes 32767 3 mediumint 3 byte 8388607 nil, 4, 11 int(11) 4 byte 2147483647 5..8 bigint 8 byte 9223372036854775807
- RSA 加密
- to_s, to_json, to_json 会把symbol :xx 转换成 “xx”, to_s 不会
[28] pry(main)> h={ [28] pry(main)* name: "hello" [28] pry(main)* } => {:name=>"hello"} [29] pry(main)> h.to_s => "{:name=>\"hello\"}" [30] pry(main)> h.to_json => "{\"name\":\"hello\"}"
- 用到的特殊方法 Array#pack ,#unpack
- to_s, to_json, to_json 会把symbol :xx 转换成 “xx”, to_s 不会
- instance method: File#read class method: File.read, constant: File::EOF
- scope :wq
render and return
- puts “sss” and return false # => nil and 后面的语句要想执行的, 则and的左部分需要返回true
查询部分字段
User.pluck(:id), 查询某个字段, 直接把数据库中的字段返回成数组,不构建Active Record 对象 User.select(:id).map(&:id), 会构建Active Record 对象检查是否存在
User.exist?(2), # id User.exist(name: ‘Tom’)Article.first.categories.any? Article.first.categories.many?
unscoped 删除所有作用域
User.unscoped.allincludes ,加载关联
User.includes(:address).all多表查询
Person .select(‘people.id, people.name, companies.name’) .joins(:company) .find_by(‘people.name’ => ‘John’) # this should be the last
- Active Record 验证结束后,所有发现的错误都可以通过实例方法 errors.messages 获取, 该方法返回一个错误集合。如果数据验证后,这个集合为空,则说明对象是合法的
- 仅字段存在才验证
allow_blank => true
or:if => lambda {|attr| attr.present?}
- 以下方法会跳过 验证
decrement! decrement_counter increment! increment_counter toggle! touch update_all update_attribute update_column update_columns update_counters
- 多个字段联合唯一验证
validates_uniqueness_of :phone, :scope => :site_id
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
支持的属性 limit:设置 string/text/binary/integer 类型字段的最大值; precision:设置 decimal 类型字段的精度,即数字的位数; scale:设置 decimal 类型字段小数点后的数字位数; polymorphic:为 belongs_to 关联添加 type 字段; null:是否允许该字段的值为 NULL;
- 可用的回调
下面列出了所有可用的 Active Record 回调,按照执行各操作时触发的顺序:
3.1 创建对象 before_validation after_validation before_save around_save before_create around_create after_create after_save 3.2 更新对象 before_validation after_validation before_save around_save before_update around_update after_update after_save 3.3 销毁对象 before_destroy around_destroy after_destroy 3.4 查找对象 after_find after_initialize 其他 after_touch 条件回调
before_save: :do_some_thing, if: :need_do? #use proc before_save :normalize_card_number, if: Proc.new { |order| order.paid_with_card? }
- 跳过回调 decrement decrement_counter delete delete_all increment increment_counter toggle touch update_column update_columns update_all update_counters
puts return nil, puts simply string represent of the object p return argument passed, output equal puts object.inspect
- arr = [1, 2, 4]
start=1, count=2
arr[start, count]
arr[-1] # last one arr[1..2] # from 1 to 2
- stack = arr.clone stack.pop # => 4
- queue = stack.clone queue.shift # => 1
In ActiveRecord, all query building methods (like where, order, joins, limit and so forth) return a so called scope.
scope with scope
scope :recent, -> { where(‘updated_at > ?’, 5.minutes.ago }scope :non_admin, -> { without_role :admin }
scope :non_admin, -> { where(admin: false) } scope :non_admin_recent, -> { non_admin.recent }
scope with multiple conditions
scope :recent, lambda { :conditions> ['updated_at > ? AND admin !
?’, 5.minutes.ago, true] }