Problem with Ecto relations with new Phoenix contexts

Guys what is going wrong here? I’m playing around with Phoenix 1.3, I’m trying to have a relationship between MyApp.Accounts.User and MyApp.Forums.Post where an user has many posts and a post belongs to an user:

schema "forums_posts" do
    field :content, :string
    field :title, :string
    field :user_id, :id
    
    belongs_to :accounts_users, MyApp.Accounts.User

    timestamps()
end
schema "accounts_users" do
    field :email, :string
    field :encrypted_password, :string
    field :name, :string
    field :username, :string
    
    has_many :forums_posts, MyApp.Forums.Post

    timestamps()
end

I have seed my DB:

Repo.insert!(%User{name: "Jon Doe", username: "jondoe", email: "jon@doe.com", encrypted_password: "12345"})
Repo.insert!(%User{name: "Jana Doe", username: "janadoe", email: "jana@doe.com", encrypted_password: "12345"})

for _ <- 1..20 do
  Repo.insert!(%Post{
    title: Faker.Lorem.sentence,
    content: Faker.Lorem.paragraph,
    user_id: Enum.random(1..2)
  })
end

But when I try to get all my Posts I get:

** (Postgrex.Error) ERROR 42703 (undefined_column): column f0.accounts_users_id does not exist
[debug] QUERY ERROR source="forums_posts" db=9.5ms queue=0.1ms
SELECT f0."id", f0."content", f0."title", f0."user_id", f0."accounts_users_id", f0."inserted_at", f0."updated_at" FROM "forums_posts" AS f0 []
    (ecto) lib/ecto/adapters/sql.ex:436: Ecto.Adapters.SQL.execute_and_cache/7
    (ecto) lib/ecto/repo/queryable.ex:130: Ecto.Repo.Queryable.execute/5
    (ecto) lib/ecto/repo/queryable.ex:35: Ecto.Repo.Queryable.all/4

What is going on here?

2 Likes

Because you database forums_posts table didn’t has a column called accounts_users_id, what it has is a “user_id”

schema "forums_posts" do
     ...

    # use correctly column name
    belongs_to :user, MyApp.Accounts.User

    # or define a foreign_key
    belongs_to :accounts_users, MyApp.Accounts.User, foreign_key: "user_id"
end
2 Likes