Created
October 5, 2017 14:09
-
-
Save ray-sh/ac6915772976bc4a534b143e37b9204d to your computer and use it in GitHub Desktop.
Build relation CURD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Build relation is very common in DB layer, like user and it's posts | |
#1> We need define the relation between Module user and posts | |
schema "users" do | |
has_many :posts, Blog.Post | |
end | |
schema "posts" do | |
belongs_to(:user, Blog.User) | |
end | |
#2> We need define the migration ops for post | |
def change do | |
alter table(:posts) do | |
add :user_id, references(:users,on_delete: :nothing) | |
end | |
end | |
#3>We need add user infomation for post CURD within post controler | |
#3.1 Build post struct from a real user struct then construct a post changeset | |
def create(conn, %{"post" => post_params}) do | |
changeset = conn.assigns.current_user | |
|>build_assoc(:posts) | |
|>Post.changeset(post_params) | |
end | |
#3.2 Get's user's posts through assoc function | |
def index(conn, _params) do | |
posts = Repo.all(assoc(conn.assigns.current_user)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment