java - In activeJDBC, how to enforce the presence of a one-to-many relationship to a model -


assuming have following db model:

car(   id             int   plaque_id      int  )  plaque(   id             int   identification text ) 

so in activejdbc, models are:

public class car extends model {      static{         validatepresenceof("plaque_id");     }      public car () {} } 

..

public class plaque extends model {          static{             validatepresenceof("identification");         }          public car () {}     } 

assuming specification says: car must have plaque.

as can see, enforcing presence of plaque_id car model.

now. when try this:

car model_s = new car(); plaque plaque_a = new plaque();  plaque_a.set("identification","a-8000"); plaque_a.saveit();  car.add(plaque_a); car.saveit(); 

i got following exception thrown:

java.lang.illegalargumentexception: can add associated model instance exists in db. save instance first, able add dependencies it.

if understand correctly, car model_s must saved first before being able link plaque plaque_a. cannot save model_s without plaque due validation rule. it's catch-22.

note: new activejdbc.

i think got backwards. since table car has column plaque_id, means plaque has many car(s), one-to-many association: http://javalite.io/one_to_many_associations.

therefore, need add car plaque, , not other way around:

car model_s = new car();    // set parameters on car plaque_a.set("identification","a-8000"); plaque_a.saveit(); plaque_a.add(model_s);  

other recommendations:

1) in java, use camelcase: models, not model_s

2) add constructor plaque:

public class plaque{    public plaque(string identification){        set("identification", identification);    }    public plaque(){} // must have default constructor } 

then code cleaner:

car model_s = new car();    // set parameters on car plaque plaque = new plaque("a-8000"); plaque_a.saveit(); plaque_a.add(models);  

generally, try avoid dynamic setters , getters, ok small project, writing permanent setters , getters amazing power of java refactoring, not have in ruby.


Comments

Popular posts from this blog

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

javascript - Confirm a form & display message if form is valid with JQuery -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -