on an ActiveModel Object, how do I check uniqueness?

前端 未结 2 969
离开以前
离开以前 2020-12-30 06:38

In Bryan Helmkamp\'s excellent blog post called \"7 Patterns to Refactor Fat ActiveRecord Models\", he mentions using Form Objects to abstract away multi-layer

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 07:28

    Creating a custom validator may be overkill if this just happens to be a one-off requirement.

    A simplified approach...

    class Signup
    
      (...)
    
      validates :email, presence: true
      validates :account_name, length: {within: 3..40}, format: { with: /^([a-z0-9\-]+)$/i }
    
      # Call a private method to verify uniqueness
    
      validate :account_name_is_unique
    
    
      def persisted?
        false
      end
    
      def save
        if valid?
          persist!
          true
        else
          false
        end
      end
    
      private
    
      # Refactor as needed
    
      def account_name_is_unique
        if Account.where(name: account_name).exists?
          errors.add(:account_name, 'Account name is taken')
        end
      end
    
      def persist!
        @account = Account.create!(name: account_name)
        @user = @account.users.create!(name: name, email: email)
      end
    end
    

提交回复
热议问题