嵌入式模型的Ecto警告

时间:2016-03-21 11:58:02

标签: elixir phoenix-framework ecto

施法时我收到此警告

  

警告:不推荐使用cast / 4进行强制转换嵌入,请使用   cast_embed / 3而不是

我有模特组织

defmodule Bonsai.Organization do
  use Bonsai.Web, :model
  alias Bonsai.OrganizationSettings

  schema "organizations" do
    field :name, :string
    field :currency, :string
    field :tenant, :string
    field :info, :map, default: %{}
    embeds_one :settings, OrganizationSettings, on_replace: :delete

    timestamps
  end

  @required_fields ~w(name currency tenant)
  @optional_fields ~w(info settings)

  @doc """
  """
  def changeset(model, params \\ %{}) do
    cast(model, params, @required_fields, @optional_fields)
    |> cast_embed(:settings)
    |> put_embed(:settings, OrganizationSettings.changeset(%OrganizationSettings{}, params[:settings] || %{}))
    |> change(%{info: params[:info] || %{}})
  end

end

我的嵌入式模型OrganizationSettings

defmodule Bonsai.OrganizationSettings do
  use Ecto.Model
  #use Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  #schema "" do
  embedded_schema do
    field :show_search_on_focus, :boolean, default: true
    field :theme, :string, default: "bonsai"
  end

  def changeset(model, params \\ %{}) do
    model
    |> cast(params, [:theme], [:show_search_on_focus])
    |> validate_inclusion(:theme, ["bonsai", "dark"])
  end

end

我尝试了很多方法但是我做错了请帮忙

2 个答案:

答案 0 :(得分:0)

请参阅https://github.com/elixir-ecto/ecto/blob/cc92f05cb2f24c3206db9017e6c28ecf77ff100d/CHANGELOG.md - 修改后的变更集。你在这里使用了弃用的cast / 4:

cast(model,params,@ required_fields,@ optional_fields) cast(model,params,[:theme],[:show_search_on_focus])

相反,请使用示例中的cast / 3和validate_required / 3。

答案 1 :(得分:0)

我已更新到Ecto 2并且更改

# mix.exs
  defp deps do
    [{:phoenix, "~> 1.1.4"},
     {:postgrex, ">= 0.0.0"},
     {:phoenix_ecto, "~> 3.0.0-beta"},
     {:phoenix_html, "~> 2.5"},
     {:phoenix_live_reload, "~> 1.0", only: :dev},
     {:gettext, "~> 0.9"},
     {:cowboy, "~> 1.0"},
     {:poison, "~> 1.5.2"}]
  end

然后运行`mix deps.update,并编辑文件

  # In file test/support/model_case.ex
  setup tags do
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(Bonsai.Repo)
  end

# In file test/test_helper.exs
#Ecto.Adapters.SQL.begin_test_transaction(Bonsai.Repo)
Ecto.Adapters.SQL.Sandbox.mode(Bonsai.Repo, :manual)

我的模型组织变更集

def changeset(model, params \\ %{}) do
    cast(model, params, [:name, :currency, :tenant])
    |> validate_required([:name, :currency, :tenant])
    |> cast_embed(:settings)
    |> put_embed(:settings, OrganizationSettings.changeset(%OrganizationSettings{}, params[:settings] || %{}))
    |> change(%{info: params[:info] || %{}})
  end