I have defined a model Essay which has a title and content.I am inserting the records as Repo.insert_all() with conflict: :nothing.I want to get the title of all the essays which didn’t conflict.Is there any way to get them?
Try passing the returning: :title
option. It only works on PG.
Thanks Jose.Does that return a list of titles or the model as in %Module.Essay{} which i have to pattern match then?
It will return a map or a struct, depending on the first parameter. In bot cases, you should be able to pattern match it out with %{title: title}
.
Thanks again Jose but it’s not working.Here’s what I did
outcome = Repo.all(Essay,listOfEssays,on_conflict: :nothing,returning: :title)
case outcome do
{numberofentries,returnedresult} -> IO.puts “Result is #{inspect returnedresult}”
end
But I am getting FuntionClauseError
When you get an error, please post the stacktrace and error message, it will help us debug it. In any case, I think the fix is that you need to do returning: [:title]
. If that doesn’t work, please post the full error.
Did you mean insert_all
?
@josevalim I am up to here
outcome = Repo.insert_all(Essay,listOfEssays,on_conflict: :nothing,returning: [:title])
case outcome do
{,%Module.Essay{title: showtitle}} -> IO.puts “Title is #{inspect title]”
{0,[]} -> IO.puts “didn’t insert anything”
{,nil} -> IO.puts “not bothered”
end
But only the second pattern is matching, even though I can see new records in the database.
Weird. However, keep in mind I wouldn’t expect any of those clauses to match in case something is returned, because Module.Essay
would be inside of a list. Try removing on_conflict: :nothing
and see what happens.
@jose thanks again …it’s working now.My pattern matching was wrong.Time to brush up on pattern matching