私はAPIのみをPhoenixアプリケーションにしています。私はRuby on Railsのバックグラウンドから来ています。Elixir/PhoenixはRailsのような強力なパラメータを制限します
私はemail
,password
,password_hash
およびrole
フィールドのユーザーモデルを持っているとします。
私は、ユーザー入力からrole
とpassword_hash
フィールドを制限、またはemail
とpassword
フィールドをホワイトリストに登録する必要があります。今誰が管理者として、この看板を投稿できる:これは通常、明示的に指定されていないフィールドを取り除くになる強いのparamsを使用して、レールに達成さ
{
"user": {
"email": "[email protected]",
"password": "testpw",
"password_hash": "shouldn't allow user input",
"role": "admin"
}
}
。
ベストプラクティスを使用してPhoenixで制限/ホワイトリストパラメータを設定するにはどうすればよいですか?
これは私の私のuser_controllerでメソッドを作成することです:
def create(conn, %{"user" => user_params}) do
changeset = User.registration_changeset(%User{}, user_params)
...
...
end
そして、ここでは、モデルの私のスキーマとチェンジで、user.ex.私はthis tutorial, it says "we pipe the new changeset through our original one"
schema "users" do
field :email, :string
field :password, :string, virtual: true
field :password_hash, :string
field :role, :string
timestamps()
end
def changeset(model, params \\ :empty) do
model
|> cast(params, ~w(email), [])
|> downcase_email()
|> unique_constraint(:email)
|> validate_format(:email, ~r/@/)
end
def registration_changeset(model, params) do
model
|> changeset(params)
|> cast(params, ~w(password), [])
|> validate_length(:password, min: 6)
|> put_password_hash()
end
フェニックスのscrub_params is close以下だが、それは私が必要なもののような音はありません。
私はこれをパターンマッチングで達成できると思いますが、どうすればよいか分かりません。
'cast'はうまくいきません。また、あなたのコントローラは 'User.registration_changeset/2'を使っていますが、' User.changeset/2'のコードを表示しています。 – tompave
あなたの 'registration_changeset'はどのように見えますか? 'changeset'は既に' params'の 'role'フィールドを無視しているはずです。 – Dogbert
'cast/3'(https://hexdocs.pm/ecto/Ecto.Changeset.html#cast/3)を' cast/4'よりも使用することをお勧めします。後者は非推奨です。 – tompave