0
首先,對不起我的英文不好。我還在學習。Ruby on Rails錯誤,當validates_uniqueness_of使用collection_select
我在DB 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表中保留日期。但是當我嘗試避免重複時,會出現錯誤。
其中@problems被設置? 'collection_select(:register,:problem_id,@problems,:id,:name,{},{:multiple => false})' – Eric
@Eric。它正在設置新的RegisterController,def new。 – Paulo