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