[SOLVED] When Ecto.Changeset action is set?

When I’m creating Post insert changeset from iex:

new_post = %MyProject.Post{}
changeset = Ecto.Changeset.cast(new_post, %{body: "Body", title: "Title"}, [:title, :body])
#Ecto.Changeset<action: nil, changes: %{body: "Body", title: "Title"},
 errors: [], data: #First.Post<>, valid?: true>

When I’m creating Post update changeset from iex:

post = MyProject.Repo.get(MyProject.Post, 5)
changeset = Ecto.Changeset.cast(post, %{body: "Body", title: "Title"}, [:title, :body])    
#Ecto.Changeset<action: nil, changes: %{body: "Body", title: "Title"},
errors: [], data: #First.Post<>, valid?: true>

It always returns action: nil. When Ecto.Changeset action is set?

1 Like

When you pass the changeset to one of the Repo functions.

2 Likes

You mean: delete(!), insert(!) and update(!), right?
I want to have it set in changeset model function (before affect database) and perform some actions (in cond do statement).
Is it possible? Or I need set it manually? Or maybe one more parameter in changeset function for cond do statement is better solution?

1 Like

I’m not sure that’s the right approach - why not create multiple changeset functions?

def create_changeset(schema, params) do
  schema
  |> common_changeset(params)
  |> create_specific_operations
end

def update_changeset(schema, params) do
  schema
  |> common_changeset(params)
  |> update_specific_operations
end

def common_changeset(schema, params) do
  # ...
end
3 Likes

ok, thx for your support, that is really helpful