1
votes

I am trying to implement :create action. Here is my codebase.

defmodule Rumbl.Repo do
  use Ecto.Repo, otp_app: :rumbl
end

for the User.ex model

defmodule Rumbl.User do

    use Rumbl.Web, :model

    schema "users" do
      field :name, :string
      field :username, :string
      field :password, :string, virtual: true
      field :password_hash, :string

      timestamps()
    end

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

end

And my controller:

defmodule Rumbl.UserController do
    use Rumbl.Web, :controller

    alias Rumbl.Repo
    alias Rumbl.User

    require Logger

    def new(conn, _params) do
        changeset = User.changeset(%User{})
        render conn, "new.html", changeset: changeset
    end

    def create(conn, %{"user" => _params}) do
        changeset = User.changeset(%User{}, _params)
        case Repo.insert changeset do
            {:ok, user} ->
                conn
                |> put_flash(:info, "#{user.name} created!")
                |> redirect to: user_path(conn, :index)
            {:error, changeset} ->
                render conn, "new.html", changeset: changeset
        end
    end

    def index(conn, _params) do
        users = Repo.all(User)
        render conn, "index.html", users: users
    end

    def show(conn, %{"id" => id}) do
      user = Repo.get(User, String.to_integer(id))
      render conn, "show.html", user: user
    end

end

Once I run my phoenix server it opens new page and when I send a request it gives me an error:

function Rumbl.Repo.insert/1 is undefined or private

What did I miss?

1
Can you try using Repo.insert(changeset) instead of Repo.insert changeset (note the extra parens). - Justin Wood
@JustinWood I doubt this is significant, since the error message clearly says it recognized the Rumbl.Repo.insert/1’s arity. - Aleksei Matiushkin
I agree, but from the provided code, I can't see anything that is amiss. - Justin Wood
Can you add some more info from the error message? Also, if you want to use the params variable in your create function, don't prefix it with a _. The _ signals that you don't care about that variable. - Frost

1 Answers

0
votes

I misunderstood underscore power in Elixir. Actually to fix an issue I have to write

sef create(conn, %{"user" => user_params}) do
        changeset = User.changeset(%User{}, user_params)
        case Repo.insert changeset do
            {:ok, user} ->
                conn
                |> put_flash(:info, "#{user.name} created!")
                |> redirect to: user_path(conn, :index)
            {:error, changeset} ->
                render conn, "new.html", changeset: changeset
        end
    end