验证Rails应用程序中的唯一字段

时间:2016-09-17 10:39:25

标签: ruby-on-rails ruby

在我的Rails应用中,我有两个模型 - UserAccount

User可以包含多个Accounts

Account包含name字段,如下图所示。

如何验证name字段对于Account是唯一的,但在数据库中不一定唯一?例如,User1可以有Account,其名称为CashUser2可以有不同的Account,但名称为Cash

user.rb:

class User < ActiveRecord::Base
  has_many :accounts

  before_save { self.email = email.downcase }

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :email, presence: true,
                    length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }

  has_secure_password

  validates :password, presence: true, length: { minimum: 6 }

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end
end

account.rb:

class Account < ActiveRecord::Base
  belongs_to :user
  has_many :balances

  before_save { self.active = true }

  validates :name, presence: true, length: { maximum: 250 },
                  uniqueness: { case_sensitive: false }

  validates :user, presence: true
end

schema.rb:

  ....
  create_table "accounts", force: :cascade do |t|
    t.string   "name"
    t.boolean  "credit"
    t.boolean  "active",     default: true, null: false
    t.datetime "created_at",                null: false
    t.datetime "updated_at",                null: false
    t.integer  "user_id"
  end

  create_table "balances", force: :cascade do |t|
    t.decimal  "balance"
    t.date     "date"
    t.integer  "account_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email"
    t.boolean  "admin"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "password_digest"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  ....

1 个答案:

答案 0 :(得分:2)

您可以使用scope

account.rb

validates :name, uniqueness: { scope: :user_id}

四个你的实际验证:

  validates :name, presence: true, length: { maximum: 250 },
                  uniqueness: { case_sensitive: false, scope: :use_id }

active record validates