Here are my schemas. A game can have multiples comments
defmodule Challenge.Games.Game do
use Ecto.Schema
import Ecto.Changeset
alias Challenge.{Ratings, Comments}
schema "games" do
field :description, :string
field :image, :string, default: ""
field :name, :string
field :promoted, :boolean, default: false
field :tags, {:array, :string}, default: []
has_many(:comments, Comments.Comment)
has_many(:ratings, Ratings.Rating)
timestamps()
end
@doc false
def changeset(game, attrs) do
game
|> cast(attrs, [:name, :description, :image, :tags, :promoted])
|> validate_required([:name, :description, :image])
end
end
defmodule Challenge.Comments.Comment do
use Ecto.Schema
import Ecto.Changeset
alias Challenge.Games.Game
schema "comments" do
field(:body, :string)
belongs_to(:game, Game, foreign_key: :game_id)
timestamps()
end
@doc false
def changeset(comment, attrs) do
comment
|> cast(attrs, [:body])
|> validate_required([:body])
end
end
And here thre create method of my controller
def create(conn, %{"comment" => comment_params}) do
game = Games.get_game!(comment_params["game_id"])
comment_changeset = Ecto.build_assoc(game, :comments, %{body: comment_params["body"]})
IO.inspect(comment_changeset)
case Comments.create_comment(comment_changeset) do
{:ok, comment} ->
conn
|> put_flash(:info, "Comment created successfully.")
|> redirect(to: Routes.game_path(conn, :show, comment_params["game_id"]))
{:error, %Ecto.Changeset{} = changeset} ->
redirect(conn, to: Routes.game_path(conn, :show, comment_params["game_id"]))
end
end
When I test the data type of the comment_changeset it’s a map so I don’t understand why I’ve got this error message :
expected params to be a :map, got: `%Challenge.Comments.Comment{__meta__: #Ecto.Schema.Metadata<:built, "comments">, body: "salut\r\n", game: #Ecto.Association.NotLoaded<association :game is not loaded>, game_id: 1, id: nil, inserted_at: nil, updated_at: nil}`
I tried inserting the changeset directly using Repo.insert() and it works but I can’t understand what is the problem with my schemas.























