1
我有以下User
模型,並且希望確保沒有人在數據庫中存儲空字符串(例如空格)。如果有人爲first_name
,last_name
或nickname
輸入「」(多個空格),則應將該屬性保存爲值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
您是否在'UserController'中使用'plug:scrub_params,「user」,...'? – Dogbert
是的,我喜歡。 aaaahhh ... http://stackoverflow.com/questions/33975229/is-phoenixs-scrub-params-like-rails-strong-parameters 謝謝! – wintermeyer
@Dogbert您能否將其作爲回答發佈? – JustMichael