donkey
donkey

Reputation: 4363

How to limit one value to appear at most once in a column in Postgresql?

How do I add a constraint or a unique index to position column in a Staff entity so that the value master can appear at most once while other values can appear however many times?

Is it even possible?

I am using Postgres database, Ruby on Rails and schema.rb.

Upvotes: 1

Views: 40

Answers (1)

margo
margo

Reputation: 2927

I'm not sure postgres enforces that kind of constraint. An alternative solution would be to set a custom validation on the model along the lines of

class SomeModel
  validate :one_master_permitted

  private
  def one_master_permitted
    errors.add(:position, "some error message") if SomeModel.find_by(position: "master")
  end
end

Upvotes: 1

Related Questions