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