[rails]rails generate指令

Kaycheng
4 min readNov 9, 2017

--

目前自己遇到容易搞混的rails指令:

rails generate scaffold List title:string description:textrails generate model List title:string description:textrails generate controller Listsrails generate migration add_items_to_lists items:string

第一個rails generate scaffold List title:string description:text

指令中,generate是產生,scaffold是架構,List是將要架設的網頁名稱(可自訂,如想架設論壇,則可以使用Article等等),這裡的List為單數!title的格式是字串(string),description的格式是文字(text)。整句話串起來的意思就是,使用rails產生(generate)一個架構(scaffold),架構的名稱為List,List中有兩種資料,一個為主題(title),使用字串格式(:string);另一個為描述(description),使用文字格式(:text)。

輸入這指令後,rails會直接將List的model/controller/views/routes都設定好,輸入網址就可以看到創建的網頁。而想改變網頁格式,只要在進入各別的page加上喜歡的設定就可以了!

  • generate可以簡寫為g。另外,若設定的格式都為string,則可以省略不寫。如上述指令,將title和description設為string的話,則可以將指令變為:rails g scaffold List title description,這樣就可以了!

第二個rails generate model List title:string description:text

這裡是使用model這個架構,輸入完後,rails會將產生model檔,並將title和description的資料加在migrate檔案下,確認無誤後,使用rails db:migrate就可以遷移到schema儲存起來。這裡的List也用單數,在model使用單數!之後再自行設定controller。

  • 在rails 5中,rake被取代為rails,所以這裡使用rails是可以的!說明如下:

For example in Rails 5 commands like db:migrate, setup, test etc which are part of rake command in Rails 4 are now being supported by rails command. However you can still choose to use rake to run those commands similar to how they were run in Rails 4. This is because Rails community has introduced Rake Proxy instead of completely moving the command options from rake to rails. -參考資料

第三個rails generate controller Lists

是使用controller這個架構,產生Lists的controller。連結上面產生model完,再產生controller的設定。這裡的Lists使用複數!

第四個rails generate migration add_items_to_lists items:string

輸入後,將會在migrate檔案下產生新的檔案,且會加入items(資料結構為string)這個項目。rails db:migrate之後,將會把items資料歸於Lists的schema檔案中。這裡的Lists為複數!

  • 這裡比較要注意的點是名稱寫法,add_xxx_to_lists,xxx可以是任何的資料名稱,也可以為_xxx_xxx(如:add_photo_items_to_lists)。然後最後的_to_lists要將配對的檔案名(如這裡對應的檔案名為Lists)寫對,這樣rails db:migrate後,才能順利將items加入Lists中!

以上指令輸入完後,都要再輸入rails db:migrate做資料的遷移!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response