Skip to content

Instantly share code, notes, and snippets.

@darui00kara
Created December 10, 2016 06:55
Show Gist options
  • Save darui00kara/e346565d535b28737fb754a551f1a880 to your computer and use it in GitHub Desktop.
Save darui00kara/e346565d535b28737fb754a551f1a880 to your computer and use it in GitHub Desktop.
Model for many-to-many and follow functions
defmodule SampleApp.User do
use SampleApp.Web, :model
alias SampleApp.Helpers.Encryption
schema "users" do
field :name, :string
field :email, :string
field :password, :string, virtual: true
field :password_digest, :string
has_many :microposts, SampleApp.Micropost
# From:1
#has_many :followed_users, SampleApp.Relationship, foreign_key: :follower_id
#has_many :relationships, through: [:followed_users, :followed_user]
# To:1
many_to_many :followed_users, SampleApp.Relationship,
join_through: "relationships",
join_keys: [follower_id: :id, followed_id: :id]
# From:2
#has_many :followers, SampleApp.Relationship, foreign_key: :followed_id
#has_many :reverse_relationships, through: [:followers, :follower]
# To:2
many_to_many :followers, SampleApp.Relationship,
join_through: "relationships",
join_keys: [followed_id: :id, follower_id: :id]
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name, :email, :password, :password_digest])
|> validate_required([:name, :email, :password])
|> validate_format(:email, ~r/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i)
|> unique_constraint(:name)
|> unique_constraint(:email)
|> validate_length(:name, min: 1)
|> validate_length(:email, max: 50)
|> validate_length(:password, min: 8)
|> validate_length(:password, max: 72)
|> set_password_digest
end
def set_password_digest(changeset) do
password = get_change changeset, :password
case password do
nil ->
changeset
_ ->
put_change changeset, :password_digest, Encryption.encrypt password
end
end
end
defmodule SampleApp.Relationship do
use SampleApp.Web, :model
schema "relationships" do
belongs_to :followed_user, SampleApp.User, foreign_key: :follower_id
belongs_to :follower, SampleApp.User, foreign_key: :followed_id
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:follower_id, :followed_id])
|> validate_required([:follower_id, :followed_id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment