datamapper / dm-validations

Library for performing validations on DM models and pure Ruby object
http://datamapper.org/
MIT License
50 stars 43 forks source link

Isn't validating an association correctly #24

Closed d11wtq closed 13 years ago

d11wtq commented 13 years ago

Given this model for a legacy schema:

class AdminUserNote
  include DataMapper::Resource

  storage_names[:default] = 'usernote'

  property :id,         Sequence,     :field => 'noteid'
  property :user_id,    Integer,      :field => 'userid'
  property :subject_id, Integer,      :field => 'subjectid'
  property :created_at, EpochTime,    :field => 'timecreated'
  property :content,    String

  validates_presence_of :content

  belongs_to :user
  belongs_to :subject, 'User', :child_key => [:subject_id]
end

For some reason, this isn't validating, with the cryptic error message of "Subjectid must not be blank":

def create
  @user = User.get!(params[:user_id])
  @note = AdminUserNote.new({
    :user => active_user,
    :subject => @user,
    :content => params[:content]
  });
  if @note.save
    redirect_to(admin_user_path(@user))
  else
    render :new
  end
end

While this is validating (passing the legacy field name directly):

def create
  @user = User.get!(params[:user_id])
  @note = AdminUserNote.new({
    :user => active_user,
    :subjectid => @user.id, # Nasty hack
    :content => params[:content]
  });
  if @note.save
    redirect_to(admin_user_path(@user))
  else
    render :new
  end
end

It's interesting that it's only the :subject property that falls victim to the bug and that :user works fine (presumably because the key name is predictable).

d11wtq commented 13 years ago

Alternatively, if I duplicate the actual legacy field name 'subjectid' in the :child_key option, this works, however the behaviour of DM allows my other way for specifying associations (it cuts down on repetition) so I guess dm-validations should behave that way too.

d11wtq commented 13 years ago

It's also odd, but this behaviour isn't observable in a real-life test; it only becomes a problem in my functional tests.

d11wtq commented 13 years ago

I realised what was happening. It was my fault and I only stumbled upon it as I started working through all of my models, replacing :child_key definitions with the actual field name, not the alias. When I got to the User model, I noticed that I had mis-typed :child_key => [:subjectid] (without the underscore). I wasn't expecting the culprit to be in the parent model, but I'll know to always check both sides of the association in future. Consider this closed! ;)