Phoenix relationship

I have a user model

schema "users" do
    field :email, :string
    field :username, :string
    field :password_hash, :string
    field :password, :string, virtual: true
    belongs_to :role, Catastore.Role
    belongs_to :store, Catastore.Store

    timestamps()
  end

and a store model

  schema "stores" do
    field :name, :string
    has_many :users, Catastore.User

    timestamps()
  end

i want to when i create a new store update the the user database. but i can’t find a way to do it with Ecto, it is not the best pratice to put the ID manually?

Try changing your schema with this:

belongs_to :store, Catastore.Store, on_replace: :update

See https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3 and https://hexdocs.pm/ecto/Ecto.Changeset.html#module-associations-embeds-and-on-replace

2 Likes

so when i update would i still use Changeset.pu_assoc or i put the id manually ?

You can do either …

1 Like

thank you just want to know the best practice. sorry for these stupid question xD

There are no stupid questions :slight_smile:

As for best practice, it’s really what suits you. Before Ecto 2, Schemas (nee Models) were everything, but as Ecto 2 has progressed schemaless queries have become better supported and more common. They really do free you up from having to turn data you already have (e.g. an id) into a struct Just Because™ the API dictates it. But … if you already have that data in a Schema struct, then go ahead and use it! The nimbleness of Ecto is quite wonderful at times.

1 Like

I see thank you. i got the clearer picture now