Hello, I’m a bit confused on how relationships work on the new Phoenix version.
In Phoenix 1.3, when we had models, we could generate one resource using $ mix phoenix.gen.json User users name:string
and also, use a reference to that table $ mix phoenix.gen.json Post posts title:string user_id:references:users
.
Then, we would simply add has_many :posts, App.Post
to our User
model and belongs_to :user, App.User
in our Post
model.
In the new version of Phoenix, with the addition of contexts, I’m a bit confused on how it works, I’ve generated an User
resource with $ mix phx.gen.json Accounts User users name:string
and a Post
resource with $ mix phx.gen.json Forums Post posts title:string accounts_user_id:references:accounts_users
.
The previous generated code will compile, however, relationships are not present, I added belongs_to :accounts_user, App.Accounts.User
to my Post
resource and has_many :forums_posts, App.Forums.Post
to my User
resource, however, it throws the following error:
Compiling 6 files (.ex)
== Compilation error on file lib/app/forums/post.ex ==
** (ArgumentError) field/association :accounts_user_id is already set on schema
And my schemas look as follows:
schema "forums_posts" do
field :content, :string
field :title, :string
field :accounts_user_id, :id
belongs_to :accounts_user, App.Accounts.User
timestamps()
end
schema "accounts_users" do
field :email, :string
field :name, :string
has_many :forums_posts, App.Forums.Post
timestamps()
end
Does someone know what is going wrong?
Thanks for the help.