ruby on rails 在model中使用enum的注意事項

來源:互聯網
上載者:User

標籤:rate   number   方便   select   cto   upd   enum   method   stat   

enum的作用是聲名一個枚舉屬性來映射資料庫裡整型欄位的值,並能通過這個屬性來查詢資料庫。

可以這麼使用(案例來自官方),比如:

class Conversation < ActiveRecord::Base  enum status: [ :active, :archived ]end
或者
class Conversation < ActiveRecord::Base enum status: { active: 0, archived: 1 }end
# conversation.update! status: 0conversation.active!conversation.active? # => trueconversation.status  # => "active"# conversation.update! status: 1conversation.archived!conversation.archived? # => trueconversation.status    # => "archived"# conversation.status = 1conversation.status = "archived"conversation.status = nilconversation.status.nil? # => trueconversation.status      # => nil

關於查詢的:
Conversation.where(status: [:active, :archived])Conversation.where.not(status: :active)

這樣使用很方便,但是使用這個enum時候一定要非常注意,你可能注意到了,它會產生一些方法。比如上面,它產生了:active!active?status= 等等。

如果你一不小心使用了:group屬性,比如這樣定義:

class Conversation < ActiveRecord::Base  enum status: {group: 0, single: 1}end

運行時它會產生You tried to define an enum named "statuss" on the model "ConfirmAsset", but this will generate a class method "group", which is already defined by Active Record.這樣的錯誤。

另外使用欄位名稱的時候也要注意,因為我得到了這樣的錯誤:You tried to define an enum named "import" on the model "ConfirmAsset", but this will generate a instance method "import=", which is already defined by another enum.

 

ruby on rails 在model中使用enum的注意事項

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.