如何使用 before_save(带参数)检查记录是否存在
How to use before_save (with params) to check if a record exist
我想检查记录是否存在 before_save,最好的方法是什么?
def create
@step = Step.new(step_params)
@course = Course.find(step_params[:course_id])
redirect_to course_path(@course) and return if step_already_present?(@step)
if @step.save
redirect_to course_path(@course.id)
else
render :new
end
end
检查方法:
def step_already_present?(step)
Step.where(poi_start_id: step.poi_start_id, course_id: step.course_id).first.present?
end
您可以对模型使用唯一性验证
如果您需要同时检查两列,您可以像这样使用范围选项:
class Step < ActiveRecord::Base
validates :poi_start_id, uniqueness: { scope: :course_id }
end
我想检查记录是否存在 before_save,最好的方法是什么?
def create
@step = Step.new(step_params)
@course = Course.find(step_params[:course_id])
redirect_to course_path(@course) and return if step_already_present?(@step)
if @step.save
redirect_to course_path(@course.id)
else
render :new
end
end
检查方法:
def step_already_present?(step)
Step.where(poi_start_id: step.poi_start_id, course_id: step.course_id).first.present?
end
您可以对模型使用唯一性验证
如果您需要同时检查两列,您可以像这样使用范围选项:
class Step < ActiveRecord::Base
validates :poi_start_id, uniqueness: { scope: :course_id }
end