Annie
Annie

Reputation: 3190

Mongoid and validation option

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.

Upvotes: 0

Views: 641

Answers (1)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

When saving your instance, the validations will be run first. This is why when saving your instance for the second time, it runs the validation against the old personality relation.

Basically, inside the Proc in your if statement, you can access your instance as it is when the validation runs. This means that if you change the personality to something else before calling @structure.update_attributes in your controller, it will use the new value.

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

Upvotes: 1

Related Questions