1
votes

I am trying to edit the locale_id field in table "users". The table "locales" contains only id, code(like "en" or "ua"), name and default timestamps.

Here is my *.eex form code:

<%= 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 %>

Controller code:

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

The schema from model "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

From model "locale":

  schema "locales" do
    field :name, :string
    field :code, :string
        has_many :users, Rumbl.User
    timestamps
  end
1
Have you specified the field in your changeset function?Gazler
Let us know what is happening when you submit the form? Do you see an error? Does the console show anything? Can you post the entire user model?Scott Swezey
@Gazler Thanks, it was missing :) Added it and everything worked fine.Александр Зарудный
@ScottS. I added locale_id to 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 and everything ran. Thank you :)Александр Зарудный

1 Answers

0
votes

I added locale_id to

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

and everything ran.