Rails学习
Rails不明记录
命名路由
- path是相对路径
- url是绝对路径
集合
字符串数组:STATES = %w(draft open closed)等同于STATES = [“draft”, “open”, “closed”] 推荐使用前者
测试 rspec、factory_girl、shoulda-matchers
rails g rspec:model order
gem "faker"
gem "factory_girl_rails", "~> 4.0"
group :development, :test do
%w[rspec rspec-core rspec-expectations rspec-mocks rspec-rails rspec-support].each do |lib|
# gem lib, :git => "https://github.com/rspec/#{lib}.git", :branch => 'master'
gem "#{lib}"
end
end
group :test do
gem 'shoulda-matchers', '~> 3.1'
gem 'capybara' #模拟操作
gem 'poltergeist' # capybara phantomjs driver
gem 'selenium-webdriver' #结合capybara,测试js
gem 'database_cleaner' #清楚测试数据
gem 'launchy' #打开浏览器
end
layout
yield :name
content_for :name
约定大于配置(比如:单复数、表之间关系等)
Gem引用
gem 'name', '~ 1.1'
gem 'name', 'git.github....'
group :development do
xxx
end
目录结构
- public:
Active Record Basics
- ORM
- 约定大于配置
- 单复数(model)
- 事务transaction 、 锁
- form_for (errors/notification等)
- 回调
Activie Record Migration
- 索引
Active Record Associations 关系
- 主键、外键
- 多态: polymorphic
- 自关联
- Controlling Caching 控制缓存
-
inverse_of 缓存数据改变控制
- belongs_to 附加方法
- include (n+1次查询)
- source/source_type
- present?/presentce/blank/count/exists?
多对多的自引用
class Friendship < ApplicationRecord
belongs_to :followers, class_name: 'User', foreign_key: :user_id
belongs_to :friends, class_name: 'User', foreign_key: :friend_id
end
class User < ApplicationRecord
has_many :friendships, class_name: 'Friendship', foreign_key: :user_id
has_many :friend_followers, class_name: 'Friendship', foreign_key: :friend_id
has_many :friends, through: :friendships
has_many :followers, through: :friend_followers# , class_name: 'Friendship', source: 'User'
end
- Relation(ActiveRecord)
- 查询(单条、多条)
- distinct去重
- limit、offset分页
- group、having(分组、分组后查询)
- reverse、unscope
- 乐观锁(可访问不可更改)、悲观锁(不可访问)
- inner、left、right、outer join
- include (预防n+1次查询)
- incldue和join区别
- Using conditionals
- pluck 神奇set、get
- to_sql 生成sql语句
- explain 性能分析
Active Model Basics
- Attribute Methods
- Callbacks
- Conversion
- Dirty
- Validations
- Naming
- Model (store_accessor)(Marshal)
- Translation
- SecurePassword
。