2014-12-02 95 views
0

我有以下型號:的ActiveRecord ::關係創建VS find_or_create_by

class MyModel < ActiveRecord::Base 

    validates :date, :my_type, presence: true 
    validates_uniqueness_of :my_type, scope: :date 

    enum my_type: { 
    "first_type": 1, 
    "second_type": 2 
    } 

end 

我想創建模型的新實例,並將其保存到數據庫:

MyModel.create!(
    date: 1.day.ago, 
    type: :first_type, 
    value: 1.50 
) 

上面的方法讓我使用枚舉來填充類型,但是我想使用find_or_create_by!方法來確保在重複的情況下不會發生錯誤。

我想這樣做(失敗):

myModel = MyModel.find_or_create_by!(
    date: 1.day.ago, 
    type: :first_type, 
    value: 1.50 
) 

我發現我能做到這樣:

myModel = MyModel.find_or_create_by!(
    date: 1.day.ago, 
    type: MyModel.my_types[:first_type], 
    value: 1.50 
) 

它看起來並不好,雖然。

爲什麼不能像創建方法一樣使用它?

回答

1

find_or_create_by很簡單,首先嚐試find_by參數,如果不能,則將它們傳遞給create

這意味着問題不在create,而是在find_by。在獲取/設置模型上的屬性時,enum提供的符號/字符串和整數之間的轉換髮生在find_by不執行的情況下。 find_by根本不知道enum提供的功能。

你上面的第二種方法是一種體面的完成你想要的方法。如果你相當擔心(而且方法名稱不長),你總是可以用下面的方式包裝它:

def self.find_or_create_by_with_my_type(type, hash)  
    find_or_create_by hash.merge(my_type: my_types[type]) 
end