I decided to create some examples for
CB Model API documentation.
Let's say we want to create a basic 1:Many entity relationship between a blog post and comments in our hypothetical blog software. 1 blog post can have 0 or many comments. Create a new empty ChicagoBoss application by running:
git clone git://github.com/evanmiller/ChicagoBoss.git
cd ChicagoBoss
make
make app PROJECT=blogy
cd ../blogy
Create a model for a blog post. Put this into src/model/post.erl
-module(post, [Id, PostTitle, PostText]).
-compile(export_all).
-has({comments, many}).
Each blog post can have many comments, CB requires that you add
-has({comments, many}). to the module declaration. Note that the comment model name must end with
s as the first element in the tuple (tag of the tuple).
Comment must belong to a post. We add a simple length of the PostId check into validation_tests/0. Put this into src/model/comment.erl
-module(comment, [Id, PostId, CommentAuthor, CommentText]).
-compile(export_all).
-belongs_to(post).
validation_tests() -> [{fun() -> length(PostId) > 0 end, "Comment must have a post."}].
(wildbill@f15)1> P1 = post:new(id, "Awesome first post", "ftw").
{post,id,"Awesome first post","ftw"}
(wildbill@f15)2> {ok, P1Saved} = P1:save().
{ok,{post,"post-1","Awesome first post","ftw"}}
(wildbill@f15)3> P1Saved:id().
"post-1"
(wildbill@f15)4> C1 = comment:new(id, P1Saved:id(), "Anonymous", "Comment text").
{comment,id,"post-1","Anonymous","Comment text"}
At this point, the shell has variable C1 representing a new comment that is associated with our first blog post.
(wildbill@f15)5> C1:belongs_to().
[{post,{post,"post-1","Awesome first post","ftw"}}]
(wildbill@f15)6> {ok, C1Saved} = C1:save().
{ok,{comment,"comment-2","post-1","Anonymous", "Comment text"}}
(wildbill@f15)7> C1Saved:belongs_to_names().
[post]