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" }
答案 0 :(得分:3)
如果我正确理解的话,那么一行最多只能有一对。尝试<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="widthinput" />
<textarea class="shorcodeval">[example width="300px"]</textarea>
scope
反之亦然,这取决于您。
答案 1 :(得分:0)
自定义验证-
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