small medium large xlarge

Img_20170307_203606_pragsmall
17 Apr 2017, 20:22
Lee Sigauke (1 post)

I’m currently on chapter 7 of programming phoenix and I seem to have hit a snag, which I have solved but it’s been bugging me why the code in the book doesn’t work for me; so if anyone can give me an answer, that would be awesome.

So the migration from the book is laid out like this

 def change do
    alter table(:videos) do
      add :category_id, references(:categories)
    end
  end

However, when I run the migration then pull all the columns from my videos table, I can never see the category_id column in my table, the only way I could get it to show/be created was to make another migration and add the category_id as an index (below)

def change do
    alter table(:videos) do
      add :category_id, references(:categories)
    end
    create index(:videos, [:category_id])
  end

Making this change also has a knock on effect on my changeset for a Category, instead of assoc_constraint, I’m having to use foreign_key_constraint.

Did I miss something here? or did something change between the version of phoenix in this book and the one I have (1.2.1)

Generic-user-small
24 Aug 2017, 19:51
Joep Stender (2 posts)

I’m also on Phoenix 1.2.1 but my migration worked fine as suggested, so no clue why it didn’t work for you. I did have some problems with the video changeset in video.ex.

The book suggests:

defmodule Rumbl.Video do
  use Rumbl.Web, :model

  schema "videos" do
    field :url, :string
    field :title, :string
    field :description, :string
    belongs_to :user, Rumbl.User
    belongs_to :category, Rumbl.Category

    timestamps
  end

  @required_fields ~w(url title description)
  @optional_fields ~w(category_id)

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> assoc_constraint(:category)
  end
end

I had to change it to make things work, following Ecto v2.2.0 documentation :

defmodule Rumbl.Video do
  use Rumbl.Web, :model

  schema "videos" do
    field :url, :string
    field :title, :string
    field :description, :string
    belongs_to :user, Rumbl.User
    belongs_to :category, Rumbl.Category

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:url, :title, :description, :category_id])
    |> validate_required([:url, :title, :description])
    |> cast_assoc(:category)
    |> assoc_constraint(:category)
  end
end
You must be logged in to comment