Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add records to an Ecto Repository through Terminal? (iex)

I've got a post model in my Phoenix Framework application.

I'd like to add records through my terminal. In Rails I can do something like this in the rails console:

u = Post.create title: "My Title", content: "Here's my content..."

What is the equivalent to this in IEX?

like image 501
Andrew Hendrie Avatar asked Dec 10 '22 17:12

Andrew Hendrie


2 Answers

first of all, you need to start your elixir terminal with

iex -S mix

make you have that -S mix or not it won't do.

after iex run, you just need to alias your module (to make it easier to access)

alias MyApp.Repo
alias MyApp.Post

after you setup the alias, you are ready to do anything you want. just test it with getting all the post with:

Repo.all(Post)

if there is no error (UndefinedFunctionError) then you can just insert your data with:

Repo.insert(%Post{title: "My Title", content: "Here's my content..."})

hope it will help you. :D

like image 99
djzz Avatar answered Feb 27 '23 15:02

djzz


Found the answer in the Phoenix Documentation.

In IEx I can do this:

post = %MyApp.Post{title: "My Title", content: "Here's my content..."}

Followed by:

MyApp.Repo.insert post  
like image 27
Andrew Hendrie Avatar answered Feb 27 '23 14:02

Andrew Hendrie