如何验证模型中的条件?

How can validate condition in a model?

我在尝试创建验证条件以不允许保存记录(如果存在)时遇到问题。

table open_courses

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

table 推动者

|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

这是控制器。

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

这是风景。

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

这是模型open_course_detail.rb

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

我也试过:

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

如果我没记错的话,你的一排不能超过一对。尝试 scope

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

或相反,由您决定。

自定义验证 -

  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