use before_create hooks

On Tuesday, October 28, 2014 7:05:29 AM UTC+3, till haxor wrote:
>
> I needed to write a record from a form via post, switch the type of data 
> in the model threw me an error saying "wrong data type" my model is this: 
>    -module (product, [
>                    id, 
>                    Name :: string () 
>                    Price :: float () 
>                    Description :: string ()]). 
>    -compile (export_all). 
>
>
>
> The idea is that by doing product:
>  new (id, Req: post_param ("name"), Req: post_param ("price"), Req: 
> post_param ("description")). 
> save the data without problem. 
>
> So I take the need to create a function that returns me all the validated 
> data and I'll leave here for whoever needs it. 
>
> # src / lib / utils_lib.erl 
> -module(utils_lib).
>
> -export([record_replace/2]).
>
> record_replace(Model,Req) ->
>         Attributes = [X || X <- boss_record_lib:attribute_names(Model),X =/= 
> id],
>         AttributeTypes = boss_record_lib:attribute_types(Model),
>         Data = lists:map(fun(X) ->
>                 Param = Req:post_param(atom_to_list(X)),
>                 Value = case proplists:get_value(X,AttributeTypes) of
>                     string -> Param;
>                     integer ->  try list_to_integer(Param) of Integer -> 
> Integer catch _:_ -> Param end;
>                     float ->  try list_to_float(Param) of Float -> Float 
> catch _:_ -> Param end;
>                     _ -> Param
>                 end,
>                 {X,Value}
>                 end,
>         Attributes),
>         [X || X <- Data, 
> proplists:get_value(list_to_atom(lists:nth(1,io_lib:format("~s",lists:map(fun(Key)
>  
> -> Key end, proplists:get_keys([X]))))),[X]) =/= []].
>
>
> to use it just do the following in the controller:
>
> product_create(Method, []) ->
>     Model = product,
>     case Method of
>         'GET' ->
>             {render_other, [{action, "product/product_create"}]};
>         'POST' ->
>             Data = utils_lib:record_replace(Model,Req),
>             Record = boss_record:new(Model,Data),
>             case Record:save() of
>                 {ok, SavedRecord} ->
>                     {redirect, [{action, "product_list"}]};
>                 {error, Errors} ->
>                     {render_other, [{action, "product/product_create"}], 
> [{errors, Errors}, {record, Record}]}
>             end
>     end.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"ChicagoBoss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
Visit this group at http://groups.google.com/group/chicagoboss.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/chicagoboss/1bf96c91-2a14-4af4-a162-02f84aca4d47%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to