首先,为我糟糕的英语道歉。我还在学习。
我有3个表在我的数据库:
问题-
has_many :registers
-
has_many :solutions, through : :registers
-
has_many :problems
-
has_many :problems, through : :registers
-
belongs_to: problem
-
belongs_to :solution
系统运行良好。我可以在所有3个表中插入新数据。
在表/模型Register
的视图中,选择问题和解决方案,我使用collection_select,如下所示:
= form_for @register do |f|
.field
= f.label :problem_id
= collection_select( :register, :problem_id, @problems, :id, :name, {}, { :multiple => false })
.field
= f.label :solution_id
= collection_select( :register, :solution_id, @courses, :id, :name, {}, { :multiple => false })
.field
= f.label :entry_at
= f.datetime_select :entry_at
.actions = f.submit
当我尝试将此验证添加到Register
时,问题才出现:
validates_uniqueness_of :student_id , scope: :course_id
得到:
> undefined method `map' for nil:NilClass
> = collection_select( :register, :problem_id, @problems, :id, :name, {}, { :multiple => false })
我不知道为什么。
因此,我尝试通过控制器进行验证:
def create
@register = Register.new(register_params)
problem_id = @register.problem_id
solution_id = @register.solution_id
if Register.exists?(['problem_id LIKE ? AND solution_id LIKE ?', problem_id, solution_id ])
render 'new'
else
@register.save
respond_with(@register)
end
end
但是错误仍然存在。
我认为原因是collection_select,但我不知道如何解决。
再说一遍,我能够在所有3个DB表中持久化日期。但是当我试图避免重复时,错误出现了
我是这样解决这个问题的:
def create
@register = register.new(register_params)
#if @register.save
# respond_with(@register)
#else
# @register = register.all
# render :new
#end
problem_id = @register.problem_id
solution_id = @register.solution_id
if register.exists?(['problem_id LIKE ? AND solution_id LIKE ?', problem_id, solution_id ])
@register = register.new
@solutions = Solution.all
@problems = Problem.all
flash[:error] = "Problem alread in the register for this solution"
render 'new'
else
@register.save
respond_with(@register)
end
end