Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. defmodule SampleApp.User do
  2. use SampleApp.Web, :model
  3.  
  4. alias SampleApp.Helpers.Encryption
  5.  
  6. schema "users" do
  7. field :name, :string
  8. field :email, :string
  9. field :password, :string, virtual: true
  10. field :password_digest, :string
  11.  
  12. has_many :microposts, SampleApp.Micropost
  13.  
  14. # From:1
  15. #has_many :followed_users, SampleApp.Relationship, foreign_key: :follower_id
  16. #has_many :relationships, through: [:followed_users, :followed_user]
  17. # To:1
  18. many_to_many :followed_users, SampleApp.Relationship,
  19. join_through: "relationships",
  20. join_keys: [follower_id: :id, followed_id: :id]
  21.  
  22. # From:2
  23. #has_many :followers, SampleApp.Relationship, foreign_key: :followed_id
  24. #has_many :reverse_relationships, through: [:followers, :follower]
  25. # To:2
  26. many_to_many :followers, SampleApp.Relationship,
  27. join_through: "relationships",
  28. join_keys: [followed_id: :id, follower_id: :id]
  29. timestamps()
  30. end
  31.  
  32. @doc """
  33. Builds a changeset based on the `struct` and `params`.
  34. """
  35. def changeset(struct, params \\ %{}) do
  36. struct
  37. |> cast(params, [:name, :email, :password, :password_digest])
  38. |> validate_required([:name, :email, :password])
  39. |> validate_format(:email, ~r/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i)
  40. |> unique_constraint(:name)
  41. |> unique_constraint(:email)
  42. |> validate_length(:name, min: 1)
  43. |> validate_length(:email, max: 50)
  44. |> validate_length(:password, min: 8)
  45. |> validate_length(:password, max: 72)
  46. |> set_password_digest
  47. end
  48.  
  49. def set_password_digest(changeset) do
  50. password = get_change changeset, :password
  51.  
  52. case password do
  53. nil ->
  54. changeset
  55. _ ->
  56. put_change changeset, :password_digest, Encryption.encrypt password
  57. end
  58. end
  59. end
  60.  
  61. defmodule SampleApp.Relationship do
  62. use SampleApp.Web, :model
  63.  
  64. schema "relationships" do
  65. belongs_to :followed_user, SampleApp.User, foreign_key: :follower_id
  66. belongs_to :follower, SampleApp.User, foreign_key: :followed_id
  67.  
  68. timestamps()
  69. end
  70.  
  71. @doc """
  72. Builds a changeset based on the `struct` and `params`.
  73. """
  74. def changeset(struct, params \\ %{}) do
  75. struct
  76. |> cast(params, [:follower_id, :followed_id])
  77. |> validate_required([:follower_id, :followed_id])
  78. end
  79. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement