我有一个简单的has_many :through
关系,并且想验证在创建Course
时至少选择了两个相关记录。 Student
通过Course
关联加入了EnrollmentAssignment
。我想选择要注册Course
表格的学生,并确认至少选择了2名学生。我正在使用simple form来处理实际的HTML / CSS验证错误,因此可能需要对该库/配置进行调整,或者可能是该库的错误。
课程
class Course < ApplicationRecord
has_many :enrollment_assignments,
class_name: 'EnrollmentAssignment',
foreign_key: 'course_id'
has_many :students,
through: :enrollment_assignments
validate :students_selected
def students_selected
self.errors.add(:student_ids, "select at least 2 students") if student_ids.size < 2
end
end
注册分配
class EnrollmentAssignment < ApplicationRecord
belongs_to :course
belongs_to :student
end
学生
class Student < ApplicationRecord
has_many :enrollment_assignments,
class_name: 'EnrollmentAssignment',
foreign_key: 'student_id'
has_many :courses,
through: :enrollment_assignments
end
现在是HTML表单字段(苗条标记,但您知道了):
= f.collection_select(:student_ids, students, :id, :name,
{include_blank: false, :include_hidden => false, :selected => @course.students.map(&:id)},
{:multiple => true})
我想确认至少选择了2个学生。自定义验证有效,因为在验证失败时检查对象时会收到错误输出:
#<ActiveModel::Errors:0x007fe70e058500
@base=
#<Course:0x007fe70c0813f8
id: nil,
name: "Whatever",
created_at: nil,
updated_at: nil>,
@details=
{:student_ids=>[{:error=>"select at least 2 students"}]},
@messages=
{:student_ids=>["select at least 2 students"]}>
但是,该错误实际上并未显示在表单中。选择HTML的形式是这样的:
<select multiple="" name="course[student_ids][]" id="course_student_ids">
<option value="1">Student 1</option>
<option value="2">Student 2</option>
</select>
正确的无效HTML输入如下所示:
<div class="form-group string required course_name form-group-invalid">
<label class="form-control-label string required" for="course_name">Name <abbr title="required">*</abbr></label>
<input class="form-control is-invalid string required" type="text" value="" name="course[name]" id="course_name">
<div class="invalid-feedback">Name can't be blank</div>
</div>
参数可以很好地使用(即使是强参数也可以),只是形式实际上不会显示错误。其他字段的验证没有问题,仅此选择字段无法正确显示。我认为这与collection_select
有关。感谢您为解决此问题提供的帮助!