2016-04-30 50 views
1

我有以下User模型,并且希望确保没有人在数据库中存储空字符串(例如空格)。如果有人为first_namelast_namenickname输入“”(多个空格),则应将该属性保存为值nil。在Rails中,我会用before_validation回调来解决这个问题。在凤凰城解决这个问题的最好方法是什么?在保存之前将空字符串转换为零

defmodule MyApp.User do 
    use MyApp.Web, :model 

    schema "users" do 
    field :first_name, :string 
    field :last_name, :string 
    field :nickname, :string 

    timestamps 
    end 

    @required_fields ~w() 
    @optional_fields ~w(first_name last_name nickname) 

    @doc """ 
    Creates a changeset based on the `model` and `params`. 

    If no params are provided, an invalid changeset is returned 
    with no validation performed. 
    """ 
    def changeset(model, params \\ :empty) do 
    model 
    |> cast(params, @required_fields, @optional_fields) 
    end 
end 
+4

您是否在'UserController'中使用'plug:scrub_params,“user”,...'? – Dogbert

+0

是的,我喜欢。 aaaahhh ... http://stackoverflow.com/questions/33975229/is-phoenixs-scrub-params-like-rails-strong-parameters 谢谢! – wintermeyer

+0

@Dogbert您能否将其作为回答发布? – JustMichael

回答

4

推荐的方法是使用scrub_params插头,其递归转换空字符串(包括那些仅由空格)成nil S代表给定的键在控制器中处理这个问题。

凤凰发电机插在生成的控制器中执行以下代码(如果控制器名为UserController):

plug :scrub_params, "user" when action in [:create, :update] 

你可以使用类似的东西。