プロジェクトの作成
rails new Project
サーバー起動
cd Project
rails server
echo "gem 'therubyracer'" >> Gemfile
bundle install
モデルの作成
rails g model user username:string password:string score:integer
rake db:migrate
モデルの動作確認
rails console
irb> User.all
irb> User.create(:username => "foo", :password => "bar", :score => 100)
irb> User.find(1)
irb> User.all.each { |u| u.delete }
コントローラの作成
rails g controller user show add
ルーティングの設定
vi config/routes.rb
コントローラの処理記述
vi app/controllers/user_controller.rb
def show
@user = User.find_by_username_and_password(params[:username], params[:password])
if @user.present?
render :json => @user
else
head :not_found
end
end
def add
@user = User.new(:username => params[:username], :password => params[:password])
if @user.save
head :ok
else
head :bad_request
end
end
モデルのバリデーション設定
vi app/model/user.rb
class User < ActiveRecord::Base
validates :username,
:presence => true,
:uniqueness => true
end
モデルにプロパティの追加
% rails g migration AddLifeToUsers life:integer
invoke active_record
create db/migrate/20121214000615_add_life_to_users.rb
% cat db/migrate/20121214000615_add_life_to_users.rb
class AddLifeToUsers < ActiveRecord::Migration
def change
add_column :users, :life, :integer
end
end
% rake db:migrate
== AddLifeToUsers: migrating =================================================
-- add_column(:users, :life, :integer)
-> 0.0009s
== AddLifeToUsers: migrated (0.0010s) ========================================
% vi app/models/user.rb