2016-04-30 49 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] 

你可以使用類似的東西。