วันศุกร์ที่ 1 เมษายน พ.ศ. 2554

rails 3: foreign key in migration

class ExampleMigration < ActiveRecord::Migration def self.up
create_table :products do |t|
t.references :category
end
#add a foreign key
execute <<-SQL ALTER TABLE products ADD CONSTRAINT fk_products_categories FOREIGN KEY (category_id) REFERENCES categories(id) SQL add_column :users, :home_page_url, :string rename_column :users, :email, :email_address
end

def self.down
rename_column :users, :email_address, :email
remove_column :users, :home_page_url
execute "ALTER TABLE products DROP FOREIGN KEY fk_products_categories"
drop_table :products
end

rails 3 : rake command on environment .

ใช้ parameter ที่ชื่อว่า RAILS_ENV ส่งค่าตาม environment ที่ต้องการตามตัวอย่างนี้

rake db:create RAILS_ENV=test
rake db:migrate RAILS_ENV=test
rake db:drop RAILS_ENV=test

วันอาทิตย์ที่ 13 มีนาคม พ.ศ. 2554

ruby: Can I set primary key in model ?

ให้ใช้ options hash ที่มี key ที่ชื่อว่า :primary_key ตามตัวอย่าง

create_table :countries ,:primary_key => :code do |t|
t.string :code, :limit => 2, :null => false
t.string :iso_a3, :limit => 3, :null => false
t.string :name, :null => false
t.timestamps
end