看板 Ruby 關於我們 聯絡資訊
※ 引述《danny8376 (釣到一隻猴子@_@)》之銘言: : ※ 引述《Pagan (test)》之銘言: : : 全新新手自己看網路資料自學中 (Ruby 2.1.5 on Rails 4.2.0) : : 想請教請教, 問題比較初級, 請多包涵 : : 一直看不是很懂ActiveRecord某些點 : : 第一) : : 對belongs_to的部分是看懂了, 依照慣例會對應到class的名稱 : : 但我有個部分不太懂, 假如是has_many 而剛好複數的字眼不是單純加上s的呢? : : 例如 (看國外範例講的 但沒看懂為什麼) : : 在article.rb中 : : belongs_to :category #這部分理解了慣例 : : 在category.rb中 : : has_many :categories #這部分不理解為何Rails會知道對應到Category class呢? : Ruby中有單複數名詞的轉換對應 : 這部分其實有不少錯誤該不該修的issue XDD : 總之就是有個轉換表/公式在 : 所以他知道 : (雖然有些錯誤在www) 補充一下,請打開 rails console : Loading development environment (Rails 4.2.0) >> "mouse".pluralize => "mice" >> "people".singularize => "person" >> "whatffffs".pluralize => "whatffffs" >> "whatffffss".pluralize => "whatffffsses" rails 的字串有 singularize / pluralize 方法來幫你做單/複數的變化 但英文有很多不規則的複數變化,若發現有錯或看不順眼 可直接打開 config/initializers/inflections.rb 來新增或修改單複數的變化 另外: >> "hello_world".camelize => "HelloWorld" >> "ProductCategory".underscore => "product_category" rails 的字串有 camelize / underscore 方法可以用,把這兩招組合起來: >> "categories".singularize.camelize => "Category" 大概是這樣 XD -- http://www.eddie.com.tw/ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.135.245.177 ※ 文章網址: https://www.ptt.cc/bbs/Ruby/M.1425110280.A.9B4.html
aquarianboy: http://goo.gl/QAPo8j 參考資料 02/28 16:04
Pagan: 感謝 太神奇了 居然有這種規則可以使用 02/28 16:30