rails new books
cd books
rails s
> http://localhost:3000
CTRL+C
rails g scaffold entry title description:text picture
rails db:migrate
rails s
> http://localhost:3000/entries
CTRL+C
vi Gemfile
> gem 'carrierwave'
bundle
rails g uploader Picture
vi app/models/entry.rb
> mount_uploader :picture, PictureUploader
vi app/views/entries/_form.html.erb
> - <%= f.text_field :picture %>
> + <%= f.file_field :picture %>
vi app/views/entries/show.html.erb
> - <%= @entry.picture %>
> + <%= image_tag(@entry.picture_url) if @entry.picture.present? %>
rails s
> http://localhost:3000/entries
rails g controller hello index
rails s
> http://localhost:3000/hello/index
CTRL+C
vi app/controllers/hello_controller.rb
> def index
> + @time = Time.now
> end
vi app/views/hello/index.html.erb
> <p>現在時刻: <%= Time.now %></p>
> <p>現在時刻: <%= @time %></p>
rails g scaffold book title:string memo:text
> http://localhost:3000/rails/info/routes
config/routes.rb
app/controllers/books_controller.rb
> http://localhost:3000/books/new
app/controllers/new.html.erb
ファイルの埋め込み
<%= render ファイル名, パーシャル内の変数名: 渡す変数 %>
<%= render 'form', book: @book %> → _form.html.erb
^
vi app/controllers/books_controller.rb
> def book_params
> + p "**********" # 見つけ易くするための目印。何でも良い。
> + p params # paramsの中身を表示
> params.require(:book).permit(:title, :memo)
> end
# 保存
book = Book.new(title: "書名", memo: "あらすじ")
book.save
# 読み込み
books = Book.all.to_a
# 検索
book = Book.where(title: "書名").first
book.title #=> "書名"
book.memo #=> "あらすじ"
Books.last
# rails内でのirb
rails c
rails g migration AddAuthorToBooks author:string
rails db:migrate
# VIEWの修正
_form.html.erb
show.html.erb
index.html.erb
# CONTROLLERの修正
books_controller.rb
# gem install *** でもよい
gem i awesome_print
# irbにて
# requireを複数回実行しても最初のみ有効
require "awesome_print"
ap [1,2,3] # 実行コマンド
# gemfile に記入する
# bundle install でもよい
bundle
# 生成される Gemfile.lock ファイルもソース管理対象
# rails内ではrequire不要
rails c
ap [1,2,3] # 実行コマンド
gem 'uglifier', '>= 1.3.0' # 1.3.0以上
gem 'coffee-rails', '~> 4.2' # 4.2.**のみ
# gemは The Ruby Toolbox で探す。アクティブなものを選ぶこと。
https://www.ruby-toolbox.com/
# rails g migration Addカラム名Toテーブル名 カラム名:型名
rails g migration AddPictureToBooks picture:string
rails db:migrate
# gemファイルに追記
gem 'carrierwave'
bundle
rails g uploader Picture
vi app/models/book.rb
> mount_uploader :picture, PictureUploader
vi app/controllers/books_controller.rb
> def book_params
> - params.require(:book).permit(:title, :memo, :author)
> + params.require(:book).permit(:title, :memo, :author、:picture)
> end
vi app/views/books/_form.html.erb
> + <div class="field">
> + <%= form.label :picture %>
> + <%= form.file_field :picture %>
> + </div>
vi app/views/books/show.html.erb
> + <p>
> + <strong>Picture:</strong>
> + <%= image_tag(@book.picture_url) if @book.picture.present? %>
> + </p>
vi app/views/books/index.html.erb
> + <th>Picture</th>
> + <td><%= book.picture %></td>
rails s