I always misread questions, so sorry if this isn’t what you’re after
When you run phx.gen.auth it allows you to create users. Each user has an ID that gets automatically generated.
When you create your tasks schema, you need to add whatever your field or fields are that the user will be submitting, but also need to create a reference to the user id
defmodule MYAPP.Repo.Migrations.CreatePosts do
use Ecto.Migration
def change do
create table(:tasks) do
add :YOUR FIELD
add :user_id, references(:users, on_delete: :delete_all)
timestamps()
end
create index(:tasks, [:user_id])
end
end
In the file containing the schema “tasks” you need to add “belongs_to :user” and replace the automatica :user field it will create.
alias MYAPP.Tasks.Task
schema "tasks" do
field :YOUR FIELD, :string
belongs_to :user, User
timestamps()
end
@doc false
def changeset(post, attrs) do
post
|> cast(attrs, [:YOUR FIELD, :user_id])
|> validate_required([])
end
In Accounts.User that is created by gen.auth you need to do similar but instead of belongs_to you have to add has_many in the same fashion
alias MYAPP.Tasks.Task
schema "users" do
*irrelevant code*
timestamps()
end
has_many :posts, Post
I’m going to assume you have a form already, are trying to figure out how to link the logged in user submitting the form and it being linked to them
If you have a logged in user, odds are you have @current_user in your socket already
After doing all of the above you can simply add the this to your “save_task” function within the form_component and it will store the logged in users ID value to the “tasks” schema’s user_id field.
If you add this before the “create_task” function it will take the task_params which contain your form data already, and update them to as a “user_id” value which will be your current users ID.
task_params = task_params
|> Map.put("user_id", socket.assigns.current_user.id)
In order for users to only see thier own tasks, you can modify the default list_tasks function to filter using the user_id field of the tasks table we created earlier.
For example
def list_tasks(current_user) do
Repo.all(
from t in Task,
where: t.user_id == ^current_user.id
)
end
When you use list_tasks in an apply_action, you just need to use list_tasks(socket.assigns.current_user)
The list_tasks function will now check the Tasks database for all user_id values that match the current_user ID value and only return values that specific to the current user.
Edit: I forgot to add that belongs_to and has_many are not the only things you can use, but sound relevant to your case. There are other options like has_one (user only has a single task) and many_to_many (if multiple of tasks are owned by multiple users for example)