hbbn623
Association not found on preloads
Hello,
I need to preload an association on a get_by function, everything seems good but in the response it tell me there is no association
Here’s the concerned code :
Schema of the association :
schema "users_cryptos" do
belongs_to :user, Accounts.User
belongs_to :crypto, Currencies.Crypto
timestamps()
end
@doc false
def changeset(user_crypto, attrs) do
user_crypto
|> cast(attrs, [:user_id, :crypto_id])
|> validate_required([:user_id, :crypto_id])
|> unique_constraint(:unique_subs, name: :subs_index)
end
Controller calling the function :
def index_by_user(conn, %{"user_id" => user_id}) do
preloads = [:cryptos, :users]
user_cryptos = Accounts.get_user_crypto_from_user!(user_id, preloads)
render(conn, "index.json", users_cryptos: user_cryptos)
end
Function in the context :
def get_user_crypto_from_user!(user_id, preloads) do
from(uc in UserCrypto, where: uc.user_id == ^user_id)
|> Repo.all
|> Repo.preload(preloads)
end
If anyone sees the problem please take meout of Elixir preloads :')
Marked As Solved
al2o3cr
Check your user_crypto.ex file - the messages suggest that Accounts.User and Currencies.Crypto aren’t being aliased correctly.
In a typical Phoenix app, they would have full names like SomeApplicationName.Accounts.User and SomeApplicationName.Currencies.Crypto and then user_crypto.ex would include:
alias SomeApplicationName.Accounts
alias SomeApplicationName.Currencies
inside the defmodule block.
Also Liked
al2o3cr
The names passed to preload should match the names of the associations you want to preload.
In your case, that would mean passing preloads = [:crypto, :user] (no s) to get_user_crypto_from_user!
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








