我有一个有几个字段的表单。在Rails端有一些工作正常的验证。但我也要求验证两个输入字段的组合。
属性为project_id
和unbillable_id
。其中只有一个应该填充一个值,因此当填充两个字段或两个字段都为空时它应该失败。我该怎么做?
这是控制器:
def create
authorize! :create, Activity
@activity = Activity.new(activity_params)
respond_to do |format|
if @activity.save
format.js { render :action => "create_success"}
else
format.js { render :action => "create_failure"}
end
end
end
这是create_failure.js.erb:
alert("Failed to upload record: <%= j @activity.errors.full_messages.join(', ').html_safe %>");
答案 0 :(得分:0)
在模型中使用callback来检查它们是否都是present?
答案 1 :(得分:0)
我假设您正在寻找XOR validation
在您的情况下,app/models/activity.rb
的行为应如下所示:
方法-1:强>
class Activty&lt;的ActiveRecord ::基
validates :project_id, presence: true, allow_nil: true
validates :unbillable_id, presence: true, allow_nil: true
validate :xor_activity
private
def xor_activity
unless (project_id.blank? ^ unbillable_id.blank?)
errors.add(:base, "Specify a Project or a Unbillable, not both")
end
end
端
方法-2:强> 形成一个数组并计算元素的数量 - https://stackoverflow.com/a/7369899/1125893
答案 2 :(得分:0)
这应该作为模型中的自定义验证存在。
#in app/models/activity.rb
validate :must_have_project_id_or_unbillable_id
def must_have_project_id_or_unbillable_id
if (self.project_id.blank? and self.unbillable_id.blank?) ||
(!self.project_id.blank? and !self.unbillable_id.blank?)
self.errors.add(:project_id, "must have either project_id or unbillable id (but not both)")
self.errors.add(:unbillable_id, "must have either project_id or unbillable id (but not both)")
end
end
答案 3 :(得分:0)
试试这个:
@activity = Activity.new(activity_params)
respond_to do |format|
if @activity.project_id.nil? && @activity.unbillable_id.nil?
format.js { render :action => "create_failure"}
elsif @activity.project_id.present? && @activity.unbillable_id.present?
format.js { render :action => "create_failure"}
elsif @activity.save
format.js { render :action => "create_success"}
else
format.js { render :action => "create_failure"}
end
end