Mongoid和验证选项

时间:2013-06-30 13:01:50

标签: ruby-on-rails mongoid

我正在使用mongoid的:if选项,如下所示:

型号:

field :categories, type: Array

belongs_to :personality

validates_presence_of :categories, :if => Proc.new{ self.personality.name == "Parking" }

查看:

<%= f.collection_select :personality_id, @personalities, "id", "name" %>
... 
<!-- TODO (JavaScript): Following checkboxes would only appear when personality "Parking" is selected -->
<input type="checkbox" name="structure[categories][]" value="Top floor" />
...
<input type="checkbox" name="structure[categories][]" value="Ground floor" />
...
<input type="checkbox" name="structure[categories][]" value="Basement" />
...

控制器:

if @structure.update_attributes(params[:structure]) 
  flash[:success] = "Structure was successfully updated."
  redirect_to admin_structure_path
else
  render :action => "edit"
end

当我尝试编辑现有记录时,如果我将个性更改为停止并且categories(复选框)中没有值,则忽略验证。在诊断之后,在我看来,它正在验证personality_id的已保存(或旧)值,而不是新更新的值。

请告知。

1 个答案:

答案 0 :(得分:1)

保存实例时,将首先运行验证。这就是为什么在第二次保存实例时,它会针对旧的personality关系运行验证。

基本上,在Proc语句中的if内,您可以在验证运行时访问实例。这意味着如果您在控制器中调用personality之前将@structure.update_attributes更改为其他内容,则会使用新值。

def update
  @structure.personality = Personality.find(params[:structure][:personality_id])
  if @structure.update_attributes(params[:structure]) 
    flash[:success] = "Structure was successfully updated."
    redirect_to admin_structure_path
  else
    render :edit
  end
end