[英]Ruby on Rails error when validates_uniqueness_of using collection_select
首先,对不起我的英语不好。 我还在学习。
我的数据库中有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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.