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.