Phoenix:changeset没有考虑外键的变化

时间:2017-11-19 14:06:21

标签: elixir phoenix-framework elixir-framework

我正在尝试更新控制台ies -S mix中记录的值。

iex> video = Repo.one(from v in Video, limit: 1)
%Rumbl.Video{...}

如果我更改了视频的标题,一切似乎都正常工作。

iex> changeset = Video.changeset(video, %{title: "some title"})
#Ecto.Changeset<action: nil, changes: %{title: "some title"}, 
errors: [], data: #Rumbl.Video<>, valid?: true>

但是更改外键似乎没有效果:

iex> changeset = Video.changeset(video, %{category_id: 3})
#Ecto.Changeset<action: nil, changes: %{},
errors: [], data: #Rumbl.Video<>, valid?: true>

我应该怎样做才能对外键进行更改?

这是模型

defmodule Rumbl.Video do
  use Rumbl.Web, :model

  schema "videos" do
    field :url, :string
    field :title, :string
    field :description, :string
    belongs_to :user, Rumbl.User, foreign_key: :user_id
    belongs_to :category, Rumbl.Category, foreign_key: :category_id

    timestamps()
  end

  @required_fields ~w(url title description)
  @optional_fields ~w(category_id)

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, @required_fields, @optional_fields)
    |> validate_required([:url, :title, :description])
    |> assoc_constraint(:category)
  end

1 个答案:

答案 0 :(得分:1)

在Ecto 2.2中,the fourth argument to cast is opts,不是可选字段。它曾经是早期的可选字段,在v2.1中已弃用,建议使用validate_required代替。这是apparently removed in v2.2.0虽然我无法在更改日志中找到它。你应该为Ecto 2.2改变你的代码:

struct
|> cast(params, @required_fields ++ @optional_fields)
|> validate_required([:url, :title, :description])

或者这样做:

@required_fields ~w(url title description)a
@optional_fields ~w(category_id)a

|> cast(params, @required_fields ++ @optional_fields)
|> validate_required(@required_fields)