Ruby on Rails 網站程式設計基礎班

Lesson 7

 

上星期講到 Scaffold 

$rails g scaffold order title:string content:text url:string 
  • 不用一行程式碼就可產生出一個簡單的 CRUD 應用

但是...

 

  • Scaffold 並不實用
  • 產生出太多你不需要的檔案
  • 很難產生出完全符合需求的程式碼 
  • 要是你的 model 有太多欄位,指令就變得很難下
  • 適合做出簡易的 CRUD 功能
  • 產生出來的程式碼適合在初學時期拿來參考

 

 

rails generater

 

  • 產生 model 和 controller 相關的檔案

rails generater

 

  • 讓 rails 幫我們產生 model 和 controller 相關的檔案

 

 

 

 

rails g model order
rails g controller orders

rails generater

 

  • 問題是那些被產出來的 test 相關檔案還是很煩...

 

 

 

 

  • 在下指令時加 --no-test-framework
rails g model post --no-test-framework
rails g controller posts --no-test-framework

rails generater 小結

 

  • Scaffold 並不實用
  • 在產生 model、controller 時可使用 rails generater
  • 為了避免產生出不必要的 test 相關檔案,在下指令時加 --no-test-framework

 

 

  • 其實把規則記熟,手動增加 model 和 controller 檔是差不多快的 (你只是多打幾個字而已)

 

rails g model post --no-test-framework
rails g controller posts --no-test-framework

Active Record Association 

 

  • 一個資料表系統用來表達現實生活中人事物的方法
  • 資料表和資料表之間通常都會有關聯性
  • 像是一個 facebook 社團(Group)和社團裡面的貼文(Post)就是一對多的關係
  • 而社團(Group)和使用者(User)之間則是多對多關係

 

 

資料表連結的秘密

 

  • 一對多關係

 

 

class Group < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :group
end
class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.integer :group_id
      t.string :title
      t.text :content
      t.timestamps
    end
  end
end
  • 多的一方,要加上 少的一方的 id:

資料表連結的秘密

 

  • 多對多關係

 

 

class Group < ActiveRecord::Base
  has_many :connections
  has_many :users, through: :connections
end
 
class Connection < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end
 
class User < ActiveRecord::Base
  has_many :connections
  has_many :groups, through: :connections
end
class CreateConnections < ActiveRecord::Migration
  def change
    create_table :groups do |t|
      t.integer :group_id
      t.string :title
      t.text :content
      t.timestamps
    end

    create_table :connections do |t|
      t.integer :group_id
      t.integer :user_id
      t.timestamps
    end
  end
end

Ruby on Rails 網站程式設計基礎班

By Eugene Chang

Ruby on Rails 網站程式設計基礎班

  • 785