在我的Rails应用中,我有两个模型 - User
和Account
。
User
可以包含多个Accounts
。
Account
包含name
字段,如下图所示。
如何验证name
字段对于Account
是唯一的,但在数据库中不一定唯一?例如,User1
可以有Account
,其名称为Cash
,User2
可以有不同的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
....
答案 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 }