Search code examples
elixirphoenix-frameworkecto

Elixir insert a record gives undefined method


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?


Solution

  • 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