I have a Post that belongs to a Venue. All Venues are unique, as determined by external_id
. When I update a Post with a Venue, if the venue exists, point to it with the foreign key venue_id on Post. If the venue does not exist, create the Venue and associate it.
I’m able to create a unique index for Venue:
create index(:venues, [:external_id], unique: true)
And my schema and changeset for a Post update is:
schema "posts" do
field :image, MyApp.ImageUploader.Type
field :uuid, :string
belongs_to :user, MyApp.User
belongs_to :venue, MyApp.Venue
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:uuid, :venue_id])
|> cast_attachments(params, [:image])
|> cast_assoc(:venue)
|> assoc_constraint(:user)
|> validate_required([:image, :uuid])
end
The schema and changeset for a venue is:
schema "venues" do
field :name, :string
field :external_id, :string
field :phone, :string
field :address, :string
field :region, :string
field :city, :string
field :postal_code, :string
field :country_code, :string
field :lat, :decimal
field :lng, :decimal
has_many :captures, MyApp.Capture
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name, :external_id, :phone, :address, :city, :region, :postal_code, :country_code, :lat, :lng])
|> validate_required([:name, :external_id, :region, :postal_code, :lat, :lng])
|> unique_constraint(:external_id)
end
I’m able to create a venue when updating the post if the venue doesn’t already exist. But if the venue already exists, I get a uniqueness error when trying to update the post. What I want, is if the venue already exists, it’d associate with the existing venue record. How do I do that?