我的Rails应用程序中有一个嵌套的表单,用于事件模型,它允许用户在事件复发时指定可重复使用的字段(另一个模型)。在创建事件时,一切都很正常,但是当事件不再发生(因此不想保存关系)时,它会给我更新事件的错误。我有重复设置,以验证字段“频率”是否存在。当没有重复时,这个字段是空白的,但是表单仍然返回,并说频率需要在那里。帮助?
class Event < ActiveRecord::Base
has_one :recurrence
accepts_nested_attributes_for :recurrence
end
class Recurrence < ActiveRecord::Base
belongs_to :event
validates :frequency, :presence => true
end事件控制器
def event_params
params.require(:event).permit(
:name, :start, :duration, :unit, :location, :description, :major,
recurrence_attributes: [ :frequency, :end ])
end
def update
@event = Event.find(params[:id])
if @event.recurrence && !params.has_key?(:has_recurrence)
@event.recurrence.destroy
end
if @event.update(event_params)
redirect_to event_path(@event)
else
render 'edit'
end
end您将注意到,它正在检查是否存在一个名为"has_recurrence“的参数--这是一个复选框标记,我在模型之外的表单中使用它来确定是否应该为事件保存递归。如果用户选中该框,表单将尝试保存重复出现,但如果他们不选中该框,则表单将不会保存重复(至少这是这样的想法)。
问题是,当我提交表单来编辑一个事件时,当事件没有重复出现,并且没有选中has_recurrence框时,它仍然试图验证重复出现的情况,并返回一个验证错误:
Recurrence frequency can't be blankUPDATE I已经根据以下答案有条件地更新了递归模型以进行验证:
class Recurrence < ActiveRecord::Base
belongs_to :event
validates :frequency, :presence => true, :if => :has_recurrence
def has_recurrence=( yesorno=false )
@has_recurrence = yesorno
end
def has_recurrence
@has_recurrence ||= false
end
end我的事件控制器中的更新如下…
def update
@event = Event.find(params[:id])
if @event.recurrence && !@has_recurrence
@event.recurrence.destroy
end
if @event.update(event_params)
redirect_to event_path(@event)
else
flash[:notice] = @event.errors
render 'edit'
end
end该视图包含以下内容,以检查是否有重复发生:
<div class="form-group">
<%= check_box_tag "has_recurrence", nil, false %> Is this a recurring event? (must check to save recurrence)
</div>
<%= f.fields_for :recurrence do |builder| %>
<%= render 'recurrence_fields', f: builder %>
<% end %>现在,当不检查递归时,我没有得到验证错误,但是递归保存到数据库(除了event_id之外,所有内容都是空的)。
发布于 2015-11-16 17:21:33
您需要一个条件验证和一个自定义属性。见:validations.html#conditional-validation。这样做可以将验证代码从控制器中取出,并返回到它所属的模型中。
基本上类似的东西(这个例子还没有测试)应该能起作用:
validates :frequency, :presence => true, :if => :has_recurrence
def has_recurrence=( yesorno=false )
@has_recurrence = yesorno
end
def has_recurrence
@has_recurrence ||= false
end就我个人而言,我会将属性重命名为has_recurrence?,但这只是简单的样式。
https://stackoverflow.com/questions/33737341
复制相似问题