Нистратов Артём
anistratov@go-promo.ru
rails g model Snippet title:string content:text
rails g scaffold
generator
model name
attribute name
attribute type
code = Snippet.new title: 'Test', content: 'a = :foo'
code.new_record?
code.save
code.id
code.persisted?
rails console
Create
h = {}
h = Hash.new
h[:foo] = 'bar'
h[:foo]
'bar'
h[:baz]
nil
h['key'] = 1
Hash
Snippet.new title: 'Test'
Snippet.new(title: 'Test')
params = { title: 'Test' }
Snippet.new params
Snippet.new({ title: 'Test' })
Method calls
code = Snippet.new
code.save
Snippet.create
git add -A
git commit -m "add Snippet model"
git checkout -b snippets
new branch name
git push origin snippets
server
branch
Snippet.find(1)
Snippet.where(title: 'Test').first
Snippet.select([:content])
.where(title: 'Test')
.order(:created_at)
.limit(1)
Read
Snippet.limit(10).pluck(:content)
Query API
.where(is_draft: false)
.where('is_draft = ?', false)
.where('is_draft = :draft',
draft: false)
.where("is_draft = #{params[:draft]}")
rails g model User name:string
rails g migration AddUserIdToSnippet user_id:integer
rake db:migrate
Relations
class User < ActiveRecord::Base
has_many :snippets
end
class Snippet < ActiveRecord::Base
belongs_to :user
end
Snippet.joins(:user)
.where(user: { name: 'John' })
.count
User.joins(snippets: :languages)
.where(languages: { name: 'Ruby' })
.take(10)
rails g model Language name:string
rails g migraion CreateSnippetsLanguages \
snippet_id:integer language_id:integer
has_and_belongs_to_many :snippets
Update
snippet.content = 'Some information'
snippet.save
snippet.updated_at
snippet.update_attributes(title: 'Yay')
snippet.assign_attributes(content: '._.')
snippet.changed
snippet.changes
Delete
snippet.destroy
Snippet.destroy(ids)
Snppet.where(title: 'Test').destroy_all
Snippet.where(title: nil).each { |post| post.destroy }
Snippet.where(...).find_each { |code| ... }
Enumerator
[1, 2, 3].each { |i| puts i * 2 }
[1, 2, 3].each do |i|
puts i * 2
end
array.map { |value| ... }
.sort.reverse.with_index
.reduce do |result, (value, index)|
...
end