我會在這裏展示一些相關的代碼模型,但如果你需要完整的代碼,你可以找到它在Github上:https://github.com/maple-leaf/phoenix_todo鳳:發佈與的has_many不斷拋出預加載錯誤
user_model:
defmodule PhoenixTodo.User do
use PhoenixTodo.Web, :model
@derive {Poison.Encoder, only: [:name, :email, :bio, :todos]}
schema "users" do
field :name, :string
field :age, :integer
field :email, :string
field :bio, :string
has_many :todos, PhoenixTodo.Todo
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name])
|> validate_required([])
end
end
todo_model:
defmodule PhoenixTodo.Todo do
use PhoenixTodo.Web, :model
@derive {Poison.Encoder, only: [:title, :content]}
schema "todos" do
field :title, :string
field :content, :string
belongs_to :user, PhoenixTodo.User
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [])
|> validate_required([])
end
end
user_controller:
defmodule PhoenixTodo.UserController do
use PhoenixTodo.Web, :controller
alias PhoenixTodo.User
def index(conn, _params) do
json(conn, User |> Repo.all() |> Repo.preload(:todos))
end
def show(conn, %{"id" => id}) do
json(conn, User|> Repo.get(id) |> Repo.preload(:todos))
end
def create(conn, data) do
user = User.changeset(%User{}, data)
#user = User.changeset(%User{}, %{name: "xxx", todos: [%PhoenixTodo.Todo{}]})
json conn, user
end
end
我可以從:index
和:show
獲得所有用戶或查詢特定用戶,但:create
將始終引發有關association
的錯誤。
請求用:curl -H "Content-Type: application/json" -X POST -d '{"name": "abc"}' http://localhost:4000/api/users
錯誤提出這樣的:cannot encode association :todos from PhoenixTodo.User to JSON because the association was not loaded. Please make sure you have preloaded the association or remove it from the data to be encoded
如何預裝:todos
當:create
?並且todos
在創建用戶時不是必填字段,我們可以忽略該關聯嗎?
你忘了做'Repo.insert'嗎?創建變更集不會將用戶插入到數據庫中。 – Dogbert
@Dogbert我認爲這不是由'Repo.insert'造成的。但我補充說,在返回json之前,並提出了相同的錯誤。並且':create'的代碼現在看起來像'user = User.changeset(%User {},data)Repo.insert(user)json conn user' – tjfdfs
是的,正如你想象的那樣,你應該傳遞用戶結構'Repo.insert'爲'json',而不是變更集。 – Dogbert