所以我對驗證有點難過。
A client has many gyms and has many memberships
A gym has many clients and has many memberships
A membership belongs to a gym and belongs to a client
對于我的一項驗證,我想將其設定為:
Validation: A client can have only one membership with gym
到目前為止,我的想法是,我需要做類似 Membership.all 并檢查 client_id == self[client_id] 或類似性質的東西。如果是這樣,則呈現 json: 錯誤“客戶具有會員資格”否則 Membership.create!(member_params)
我覺得我現在想多了,這種情況必須有一個有效的速記
我有點不確定該怎么做。任何幫助將不勝感激!
uj5u.com熱心網友回復:
我希望你的模型看起來像這樣:
class Client < ApplicationRecord
has_many :memberships
has_many :gyms, through: :memberships
end
class Gym < ApplicationRecord
has_many :memberships
has_many :clients, through: :memberships
end
class Membership < ApplicationRecord
belongs_to :client
belongs_to :gym
end
要添加一個客戶只能同時擁有一個健身房會員資格的唯一驗證,請在Membership
模型中添加以下行:
validates :client_id, uniqueness: { scope: :gym_id }
此外,我建議為資料庫中的這些列添加唯一索引:
add_index :memberships, [:client_id, :gym_id], unique: true
uj5u.com熱心網友回復:
您需要會員級別的唯一性,如下所示:
class Membership < ApplicationRecord
belongs_to :client
belongs_to :membership
validates :gym_id, uniqueness: {scope: :client_id}
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507276.html
標籤:轨道上的红宝石 验证 rails-activerecord
上一篇:訓練期間cuda記憶體不足
下一篇:資料等處理