[英]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.