twobeers

twobeers

Need help understanding table relations in Ecto

i am struggling with ecto these days… i really do not understand concepts :frowning:

For a demo I startet a project with a single DB table.. and fine this worked, I was happy what can be done in really a short amount of time with elixir / phoenix.

But then I just want to structure this single Table. One field, named “parameterset” should be populated flexible in a new table parametersets and should be just referenced from my “main” table. (just a first step). Outside (Form view) there is only a selection possible from entries in this table. Both are connected throw a ID (by default i think). So just a simple lookup for values in second table.

So i read and tried and read, and tried.. edited the changeset function, my its a wrong place. no.. how i have to do this??? I have posted the code from the schema below. This Ecto (changeset, …) is a blackbox for me. really hard to get in my brain.

schema "parametersets" do
  field :name, :string
  has_many :parameter, ProberParameterfileAssembler.Parameter.Posts
  timestamps()
  end
end

defmodule ProberParameterfileAssembler.Parameter.Posts do
  use Ecto.Schema
  import Ecto.Changeset

  schema "parameters" do
    field :address, :integer
    field :description, :string
    field :value, :integer
    timestamps()
    belongs_to :parameterset, ProberParameterfileAssembler.Parameter.Parameterset
  end

  @doc false
  def changeset(posts, attrs) do
    posts
    |> ProberParameterfileAssembler.Repo.preload(:parameterset)
    |> cast(attrs, [:address, :value, :description, :parameterset])
    |> cast_assoc(:parameterset)
    |> validate_required([ :value, :description])
  end

currently i am getting protocol Phoenix.HTML.Safe not implemented for #Ecto.Association.NotLoaded<association :parameterset is not loaded> of type Ecto.Association.NotLoaded (a struct) error.

Most Liked

sbuttgereit

sbuttgereit

Everything I read in your posts suggest that you’re finding the role of Changesets confusing.

Changesets are all about validating that a set of proposed changes meet the criteria that you set. There’s a little bit more to it than that in that often times a Changeset will determine if there’s even a change at all being made as compared to a starting data struct you provide, but not much more than that. A Changeset is not really involved in questions of data retrieval. Preloads on the other hand are involved in data retrieval.

So, for example, in the Changeset you posted, the validate_required/3 call you made says that any proposed change that is validated by the Changeset must include values for :value and :description. These values may come from the starting data or be part of the change you’re validating, but they must have a value. The cast/4 and cast_assoc/3 calls are doing the initial comparison of the posts argument (the original or starting data struct, the struct before the proposed changes) and the attrs argument which is the map containing the changes you want to make to posts. The casts produce an initial Changeset struct which has figured out what exactly is changing (if anything). Eventually the Changeset struct is passed on a function like insert/2 or update/2 and if all of the validations in the Changeset were passed, the insert or update takes place… if the Changeset failed in one of its requirements, then the insert/update doesn’t happen and you get a corresponding failure return result from those functions.

preload/3 on the other hand is about data retrieval. As others have mentioned, associated data is not automatically loaded in a query, you have to ask for it to be “preloaded”. Repo.preload/3 is used after you have already retrieved data from a query but without preloaded associations at query time: you can ask for that data after the fact. Ecto.Query.preload/3 allows you to ask for the preload in the query itself (see Ecto.Query.from/2). Changesets are not used in data retrieval so preload doesn’t apply.

Our answers may have been a bit confusing, too, because while Changesets aren’t involved in data retrieval, an insert or update can return a data struct if requested (and if using a database that supports it) via the returning: true option. If you get data back from the insert or update that way, I would expect that you could then use Repo.preload/3 to load the associations from that returned data.

LostKobrakai

LostKobrakai

As a bit of additional context: Differently to other ORMs or db libraries in various languages ecto does not automatically load relationships. Those fields by default are populated with the Ecto.Association.NotLoaded struct and are only filled with real data once you explicitly load the associations using preload – giving you the tools to prevent n+1 queries from the start.

joshdcuneo

joshdcuneo

This error is likely coming from a template somewhere. When your ProberParameterfileAssembler.Parameter.Posts struct does not have the parameterset association loaded the value of the :parameterset key on that struct would be an Ecto.Association.NotLoaded struct.

If you look in your templates for something like <%= @post.parameterset %> you can probably find the location where the error is raised.

In order to display the parameterset you will need to load the association, possibly by using Repo.preload/3 which is documented here and then render the values.

<%= @post.paremeterset.address %>
<%- @post.parameterset.description %>

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New

Other popular topics Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement