Ruby on Railsの最初の一歩。
2017年1月7日
Rubyのインストールをして、Railsのインストールも出来たので、次はRailsを起動してみたいと思います。
とりあえず動く環境を作りたいので、DBはMySQLではなく一旦SQLiteで。
アプリの作成
testって名前のアプリを作ってみましたw
rails new test |
必要なモジュールは以下でまるっとインストール。
bundle install |
で、エラーが発生しました。
あれ・・SQLiteが無い??
checking for sqlite3.h... no sqlite3.h is missing. Try 'brew install sqlite3', 'yum install sqlite-devel' or 'apt-get install libsqlite3-dev' and check your shared library search path (the location where your sqlite3 shared library is located). |
とりあえず言われた通りに、sqlite-develをインストールしました。
yum install sqlite-devel |
再度、bundle install。
bundle install |
Rails起動!
rails s |
とりあえず起動はできたので、コントローラーを追加してみます。
コントローラーの追加
usersクラスの中にindexとshowの2つのメソッドを生やします。
rails g controller users index show |
DB作成
rakeコマンドでdbを作成。
rake db:create |
モデルの作成
user(table)にname,username,location,about(カラム)を用意。
rails g model user name:string username:string location:string about:text |
マイグレート
上で作成したテーブルをDBに流し込みます。
rake db:migrate |
デフォルトデータ
初期データとして、seeds.rbの中にuserの中身を入れてみました。
@user = User. new @user .name = 'aaa' @user .username = 'bbb' @user .location = 'ccc' @user .about = 'ddd' @user .save |
デフォルトデータを流し込む
rake db:seed |
Active Record
User.find_by( :username => 'aaaa' ) # usernameがaaaaのレコードを取得 User.find( 1 ) # idが1のレコードを取得 User.all # 全部のレコードを取得 |
コントローラーからリダイレクトをしたいっ!
redirect_to '/hogehoge/index' |
一旦触ったとこまでをメモしましたが、あとで追記するかも。
(もしくは別のページにまとめた方がいいかな・・)