Ezio Auditore
Ezio Auditore

Reputation: 169

How can validate condition in a model?

I'm having issue trying to create a validate condition to not allow to save records if it exists.

table open_courses

|id|   |name|
  1     Course 1
  2     Course 2

table movers

|id|  |name|
  1  mover 1
  2  Mover 2

table open_course_deails

|id| |open_course_id|  |mover_id
  1        1                1    #correct save
  2        2                1    #correct save
  3        1                2    #correct save
  4        2                2    #correct save
  5        1                1    #should not save the information
  6        1                2    #should not save the information
  7        2                1    #should not save the information
  8        2                2    #should not save the information

Here is the controller.

def new
  @open_course_detail= OpenCourseDetail.new
end

def create
  @open_course_detail.new(open_course_params)
  if @open_course.save
    redirect_to :index
  end
end

Here is the view.

<%= form_for @open_course_detail do |f| %>
  <%= f.text_field :open_course_id  %>
  <%= f.text_field :mover_id  %>  
<$ end %>

Here is the model open_course_detail.rb

validates :open_course_id,:uniqueness => { message => "Already in use" }

Also I tried:

 validates :mover_id,:uniqueness => { message => "Already in use" }

Upvotes: 0

Views: 42

Answers (2)

Anand
Anand

Reputation: 6531

Custom validation -

  class OpenCourseDeails < ApplicationRecord

      validate :record_present

      def record_present
        records = OpenCourseDeails.where("open_course_id = ? AND mover_id = ?", self.open_course_id, self.mover_id)
        if records.present?
          errors.add(:record, "Already present!")
        end
      end

  end

Upvotes: 0

Ursus
Ursus

Reputation: 30071

If I got it correctly you can't have more than one pair for a row. Try scope

validates :open_course_id, :uniqueness => { :message => "Already in use", :scope => :mover_id }

or the other way around, it's up to you.

Upvotes: 3

Related Questions