mithereal

mithereal

Association help

hello i am having issues with loading nested associations im sure its been answered befor sorry for repeating if so i looked and could find nothing calendar events have jobs which have associated start and end locations
when i inspect like in the example i get nil association not loaded, am i not loading these associations correctly?

defmodule Site.CalendarEvent do
  use Site.Web, :model


  schema "calendar_event" do

      field :title, :string
      field :allDay, :string
      field :start, :string
      field :end, :string
      field :url, :string
      field :className, :string
      field :editable, :string
      field :startEditable, :string
      field :durationEditable, :string
      field :resourceEditable, :string
      field :rendering, :string
      field :overlap, :string
      field :uuid, :string
      field :constraint, :string
      field :source, :string
      field :color, :string
      field :backgroundColor, :string
      field :borderColor, :string
      field :textColor, :string
      field :date, Calecto.DateTime
      field :datetime, Calecto.DateTime
      field :posted_on, Calecto.DateTime

    timestamps()

    belongs_to :user, Site.User
    belongs_to :job, Site.Job
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:start, :uuid, :user_id, :title, :job_id])


  end
end

defmodule Site.Location do
use Site.Web, :model

  schema "locations" do
    field :address, :string
    field :city, :string
    field :state, :string
    field :zip, :string
    field :customer_id, :integer
    field :apt, :string
    belongs_to :job, Site.Job


    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [ :address,  :city,  :state,  :zip, :customer_id, :job_id, :apt  ])
    |> validate_required([ :address, :city,  :state,  :zip])
    |> foreign_key_constraint(:customer)
  end
end

defmodule Site.Job do
  use Site.Web, :model

  schema "jobs" do

      field :type, :string

      field :status, :string
      field :uuid, :string

     field :amount, Money.Ecto.Type

    timestamps()
    has_one :calendar_events, Site.CalendarEvent
    has_one :lead, Site.Lead
    belongs_to :start_location, Site.Location
    belongs_to :end_location, Site.Location
    belongs_to :customer, Site.Customer
    belongs_to :user, Site.User
    has_many :events, Site.JobEvents
    has_many :locations, Site.Location
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:total_distance, :move_weight,  :type, :amount, :customer_id, :status, :user_id, :uuid, :start_location_id, :end_location_id])
    |> validate_required([:total_distance, :move_weight,  :type, :amount, :customer_id])
  end

    def updatechangeset(struct, params \\ %{}) do
      struct
          |> cast(params, [:uuid, :user_id, :status])


    end

      def locationschangeset(struct, params \\ %{}) do
      IO.inspect(params, label: "params")
          struct
              |> put_assoc(:start_location, params["start_location"])
              |> put_assoc(:end_location, params["end_location"])

        end
end

in the controller i have a function that i post to

def calendar(conn, params) do
import Ecto.Query, only: [from: 2]
user_id = conn.assigns.current_user.id


jobs = Site.Repo.all from e in CalendarEvent,
   where: e.user_id == ^user_id,
   preload: [job: :start_location, job: :end_location]

   render(conn, "booked.json", events: jobs )
  end

and in the view i serialize the json in the view as followes

def render("booked.json", %{events: events} ) do

events = case events do

nil -> []
_->  Enum.map(events, &events_json/1)
end
end

def events_json(event) do
job = event.job
IO.inspect(job, label: "event")
lead = job.lead
start_location = job.start_location
end_location = job.end_location

start_string = start_location.address <> " " <> start_location.city <> ", " <> start_location.state <> " " <> start_location.zip
end_string = end_location.address <> " " <> end_location.city <> ", " <> end_location.state <> " " <> end_location.zip

miles = to_string (ParseTransform.to_miles(job.total_distance))
title = "title"


        %{
          title:  title,
          description:  title,
          start: event.start,
          end: event.end,
          url: event.url ,
          from: start_string,
          to: end_string,
          className:  event.className ,
          editable:   event.editable ,
          startEditable:  event.startEditable ,
          durationEditable: event.durationEditable ,
          resourceEditable: event.resourceEditable ,
          rendering:       event.rendering ,
          overlap:   event.overlap ,
          constraint:   event.constraint ,
          source: event.source ,
          color:       event.color  ,
          backgroundColor: event.backgroundColor,
          borderColor:     event.borderColor,
          textColor:    event.textColor ,
          date:    event.date ,
          datetime: event.datetime,
          posted_on: event.posted_on
        }
      end

Where Next?

Trending in Questions Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
tj0
I’ve been following the steps here for the upgrade from 1.6 to 1.7 and it has gone relatively smoothly all the way till the phoenix_view ...
New
cgraham
Hi! What is currently the best library/method for parsing text and tabular data out of PDF files in Elixir or Erlang?
New
stefanchrobot
Hi, I need a way to handle data migrations in my application. I found an article by @wojtekmach about manual migrations: Automatic and ma...
New
stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
webofbits
Squid Mesh is an open source workflow automation runtime for Elixir applications. It is aimed at Phoenix and OTP apps that want to defin...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
kip
In 2021 I started a new library called Tempo with the objective of modelling time as a set of intervals - not as instants. In 2022 I gave...
New

We're in Beta

About us Mission Statement