Saving from post_param into model with data type

26 views
Skip to first unread message

till haxor

unread,
Oct 28, 2014, 12:05:29 AM10/28/14
to chica...@googlegroups.com
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.


can2nac

unread,
Oct 28, 2014, 11:08:49 AM10/28/14
to chica...@googlegroups.com
use before_create hooks
Reply all
Reply to author
Forward
0 new messages