Home > Mobile >  Rails Validations. Gym/Client/Membership
Rails Validations. Gym/Client/Membership

Time:09-07

So I'm a little stumped on a validation.

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

For one of my validations I'd like to set it up as so:

Validation: A client can have only one membership with gym

My thought so far being, I need to do something like, Membership.all and check if a client_id == self[client_id] or something of that nature. If so then render json: error "client has membership" else Membership.create!(member_params)

I feel like I'm overthinking at the moment and there must be a validates shorthand for such a situation

I'm a little unsure of how to go about this. Any help would be greatly appreciated!

CodePudding user response:

You need uniqueness in the membership class, like this:

class Membership < ApplicationRecord
  belongs_to :client
  belongs_to :membership
  validates :gym_id, uniqueness: {scope: :client_id}
end

CodePudding user response:

I expect your models to look like this:

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

To add the unique validation that one client can only have one membership with a gym at the same time add the following line to Membership model:

 validates :client_id, uniqueness: { scope: :gym_id }

Additionally, I suggest adding a unique index to those columns in the database:

add_index :memberships, [:client_id, :gym_id], unique: true

CodePudding user response:

validates :client_id, uniqueness: true

whelp here it is

  • Related