rock
rock

Reputation: 378

How to prevent creating duplicate row in Rails?

project_site model has attributes like site_id, project_id and attendance_month.

Before saving data into table, I want to check if same row already exists then I want to add error.

If same row doesn't exists, then I want to add row into table. I tried validate method on create but it did not work.

Current code in model:

project_site.rb

validates :attendance_month, :project_id, :site_id, presence: true
belongs_to :user

Upvotes: 1

Views: 52

Answers (1)

Rockwell Rice
Rockwell Rice

Reputation: 3002

If I am understanding the question correctly, you only want one record in the DB for a :attendance_month, :project_id, and :site_id record combination?

I would do this

Add a custom validation in the model

validate :validate_record_is_unique

Then for the method itself (you can change the message to whatever you want it to be obviously)

def validate_record_is_unique
  # Check if a matching record exists
  rec = ProjectSite.where('attendance_month = ? AND project_id = ? AND site_id = ?', self.attendance_month, self.project_id, self.site_id)

  if rec.count > 0
    errors.add :attendance_month, 'A record for this site and project already exist for that month.'
  end
end

Upvotes: 2

Related Questions