Rails

プロジェクトの作成

$ rails depot
$ mysql -u root
mysql> create database depot_developmet;
mysql> create database depot_test;
mysql> create database depot_production;

コンフィグの変更

host行の下の三箇所に、以下の行を追加

  socket: /var/run/mysqld/mysqld.sock

テーブルの作成

  • depot/db/create.sql
drop table if exists products;
create table products(
	id		int		not null auto_increment,
	title		varchar(100)	not null,
	description	text		not null,
	image_url	varchar(200)	not null,
	price		decimal(10,2)	not null,
	primary key (id)
);
  • scaffoldを作成しようとしたら、テーブルがないとエラーになったので、とりあえず...。要調査。
$ rake migrate

Scaffoldの作成

$ ruby script/generate scaffold Product Admin
$ script/server 

テーブルの変更

  • data_available datetime not null,を追加
  • mysql -u root depot_development < db/create.sql
  • ruby script/generate scaffold Product Admin
    • overwrite app/views/admin/_form.rhtml? [Ynaq] a

Validate

  • app/models/product.rb
class Product < ActiveRecord::Base

  validates_presence_of :title, :description, :image_url
  validates_numericality_of :price
  validates_uniqueness_of :title
  validates_format_of :image_url,
                      :with  => %r{^http:.+.(gif|jpg|png)$}i,
                      :message => "must be a URL for a GIF, JPG, or PNG image"

  protected
  def validate
    errors.add(:price, "Should be positive") unless price.nil? || price >= 0.01
  end
end