2016-03-03 62 views
1

考慮下面的ActiveRecord模型與enum柱:如何爲活動記錄枚舉指定默認值?

class User < ActiveRecord::Base 
    enum role: [:normal, :sales, :admin] 
end 

如何設置爲role之前保存到數據庫的默認值。

例如:

user = User.new 
puts user.role # Should print 'normal' 
+1

是否有你需要保存到數據庫之前做了具體的原因是什麼?這可以在將記錄保存到db期間完成嗎? – uday

回答

3
class User < ActiveRecord::Base 
    enum role: [:normal, :sales, :admin] 

    after_initialize do 
    if self.new_record? 
     self.role ||= :normal 
    end 
    end 
end 

或者如果你喜歡

class User < ActiveRecord::Base 
    enum role: [:normal, :sales, :admin] 

    after_initialize :set_defaults 

    private 

    def set_defaults 
    if self.new_record? 
     self.role ||= :normal 
    end 
    end 
end 

注意,我們使用|| =來防止after_initialize破壞任何傳遞的內容在使用User.new進行初始化期間(some_params)

+0

當用角色初始化對象時會發生什麼:'User.new(role:'sales')'? –

+1

該死的你是對的。 after_initialize會跺腳參數...所以我需要一個|| =不會覆蓋它。更新我的答案。 –

1

您可以使用此回調,before_save

class User < ActiveRecord::Base 
    before_save :default_values 

     def default_values 
      self.role ||= "normal" 
     end 
end 
+0

用你的代碼'user = User.new; user.role'將返回'nil'。 –

+0

爲什麼不嘗試通過遷移將現有列添加默認值。 – BENS

+0

保存模型後,數據庫中設置的默認值僅適用於**。 –

2

您可以在遷移文件中將其設置爲:默認爲'normal'。

一點很好的例子:LINK

class User < ActiveRecord::Base 
    enum role: [:normal, :sales, :admin] 

    #before_save {self.role ||= 'normal'} 
    # or 
    #before_create {self.role = 'normal'} 
end