0

I am using :if option with mongoid like the following:

Model:

field :categories, type: Array

belongs_to :personality

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

View:

<%= 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" />
...

Controller:

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

When I try to edit existing record, it ignores the validation if I change personality to Parking and there is no value in categories (checkboxes). After diagnosing, it appears to me that it is validating against saved (or old) value of personality_id instead of the newly updated one.

Please advise.

4

1 回答 1

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
于 2013-06-30T13:54:43.590 回答