凤凰选择表单控件无效

时间:2016-05-22 19:56:47

标签: elixir phoenix-framework changeset

我正在尝试编辑表“users”中的locale_id字段。 表“locales”仅包含id,代码(如“en”或“ua”),名称和默认时间戳。

这是我的* .eex表单代码:

<%= form_for @changeset, user_path(@conn, :update, @current_user), [multipart: true], fn f -> %>
...
<div class="form-group">
    <label>Language</label>
    <%= select f, :locale_id, @locales, class: "form-control" %>
</div>
...
<% end %>

控制器代码:

plug :load_locales when action in [:new, :create, :edit, :update]

...

def edit(conn, %{"id" => id}) do
  user = Repo.get!(Rumbl.User, id)
  changeset = Rumbl.User.changeset(user)
  render(conn, "edit.html", user: user, changeset: changeset)
end

def update(conn, %{"id" => id, "user" => user_params}) do
  user = Repo.get!(Rumbl.User, id)
  changeset = Rumbl.User.changeset(user, user_params)

  case Repo.update(changeset) do
    {:ok, user} ->
      conn
      |> redirect(to: user_path(conn, :show, user))
    {:error, changeset} ->
      render(conn, "edit.html", user: user, changeset: changeset)
  end
end

defp load_locales(conn, _) do
  locales = Repo.all from(c in Rumbl.Locale,
                          order_by: c.id,
                          select: {c.name, c.id})
  assign(conn, :locales, locales)
end

模型“user”的架构:

  schema "users" do
    field :name, :string
    field :username, :string
    field :password, :string, virtual: true
    field :password_hash, :string
    belongs_to :locale, Rumbl.Locale
    has_many :friends, Rumbl.Friend
    has_many :devices, Rumbl.Device
    timestamps
  end

从模型“locale”:

  schema "locales" do
    field :name, :string
    field :code, :string
        has_many :users, Rumbl.User
    timestamps
  end

1 个答案:

答案 0 :(得分:0)

我将locale_id添加到

def changeset(model, params \\ :empty) do
  model
  |> cast(params, ~w(name username locale_id), [])
  |> unique_constraint(:username)
  |> validate_length(:username, min: 1, max: 20)
end

一切都在运行。