I have a csv file with a list of users and the following import method inside UserController and I would like to import these users by submitting the csv file with a form. And It looks like I'm doing it wrong.
users_controller
def import(conn, %{"user" => user_params}) do
user_params["file"]
|> File.stream!()
|> CSV.decode
|> Enum.each(fn(user) -> User.changeset(%User{}, %{name: Enum.at(user, 0), email: Enum.at(user, 1)}) |> Repo.insert end)
conn
|> put_flash(:info, "Imported")
|> redirect(to: user_path(conn, :index))
end
routes
post "/import", UsersController, :import, as: :import_csv
form
<%= render "import_form.html", changeset: @changeset,
action: import_csv_path(@conn, :import) %>
-
<%= form_for @changeset, @action, [multipart: true], fn f -> %>
<div class="form-group">
<%= label f, :file, class: "control-label" %>
<%= file_input f, :file %>
</div>
<div class="form-group">
<%= submit "Submit", class: "btn btn-primary" %>
</div>
<% end %>
model
schema "users" do
field :name, :string
field :email, :string
field :file, :any, virtual: true
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name, :email, :file])
|> validate_required([:name, :email])
|> unique_constraint(:email)
end
The following code works from iex
def import(file) do
file
|> File.stream!()
|> CSV.decode
|> Enum.each(fn(user) -> User.changeset(%User{}, %{name: Enum.at(user, 0), email: Enum.at(user, 1)}) |> Repo.insert end)
end
no function clause matching in IO.chardata_to_string/1but the answer below solved the problem. I needed to selectpath. ty - kirqe