2016-08-05 2 views
1

列挙型で、特定の種類の一意性を検証します:私は一つだけ:deposit:withdrawal、そして:feeアカウントが存在することを確認する必要がありRailsは:どのように私は、次の列挙型を持つモデル持って

# Schema 
# account_type :integer, not null 

enum account_type: { 
    user: 1, 
    deposit: 2, 
    withdrawal: 3, 
    fee: 4 
} 

を、しかし、無制限の数の:userアカウントを許可します。これをモデルの検証とどうすればいいですか?

答えて

2
validates :account_type, uniqueness: true, if: 'account_type == "user"' 

に条件を渡すことができますそれを修正するよう要求します。

0
class MyModel < ActiveRecord::Base 

    validate :only_one_of_most_account_types 

    def only_one_of_most_account_types 
    return if account_type == 1 
    match = MyModel.find_by(account_type: account_type) 
    errors.add(:account_type, "Already have one of these") if match && match.id != id 
    end 

end 
1

あなたはそれ自体が間違っていた、と彼は私に応答しませんでしたが、答えは、@のneydroidの回答に基づいた独自性の検証

validates :account_type, uniqueness: true, if: '!account_type.user?' 
+1

短く甘いですが、これはうまくいかず、条件文に '? 'を追加すると構文エラーがスローされます。あなたの答えの条件を ''account_type ==" user "''に変更すれば、私はそれを受け入れます。 – amingilani

関連する問題