Tuesday, August 16, 2011

Validation errors in Rails

Whoa! I've been chugging along with Manticore the last 5 days or so and making some good progress. However, I've hit another wall (can you believe it?)

Basically here's the problem. I have a model Ac that creates Armor information for a Character. I've created some methods to calculate various data from fields from a Character's Ac model, and to avoid any errors when doing these calculations I need to validate presence_of and numericality_of several fields.

So my problem is two-fold. First off, when creating the Ac, all of the validation errors appear before the user has attempted to enter any data. Furthermore, the user can still create an Ac with no data at all. Clearly my validation isn't working.

Here's the code itself from my Ac model:

class Ac < ActiveRecord::Base
belongs_to :character
validates_presence_of :base_ac, :armor, :shield, :dex, :size, :natural, :misc, :deflection validates_numericality_of :base_ac, :armor, :shield, :dex, :size, :natural, :misc, :deflection

...
end


And the code from my AcsController:

class AcsController < ApplicationController
def new
  @character = Character.find(params[:character_id])
  @ac = @character.create_ac(params[:ac])
end

def edit
  @character = Character.find(params[:character_id])
  @ac = @character.ac
end

def create
  @character = Character.find(params[:character_id])
  @ac = @character.ac(params[:ac])
  redirect_to character_path(@character), :notice => 'Armor Class was successfully created.'
end

def update
  @character = Character.find(params[:character_id])
  @ac = @character.ac
  if @ac.update_attributes(params[:ac])
    redirect_to character_path(@character), :notice => 'Armor Class was successfully updated.'
  else
    render :action => "edit"
    end
  end

end

I'm not sure what could be causing this problem. I've got similar validation for the Character model and it works fine. Any advice? The form_for a new Ac is rendered from a partial in the Character show page, but I'm not sure if that would have an effect on this.

Also, on a slightly tangential note, when rendering a form like this, is that what's meant by a "nested form" ? I've seen this term a few times while searching for a solution and I'm unclear as to what it means.

Here's a link to the project on Github: https://github.com/illbzo1/Manticore