필드에 여러 이미지를 첨부하려고합니다. 이미지 모델에 대한 연결을 쉽게 만들 수 있지만 맵 / 배열 필드를 사용하여 동일한 작업을 수행 할 수있는 방법을 알고 싶습니다.
모델은 다음과 같습니다.
schema "users" do
field :images, {:array}
end
def changeset(user, params \\ :invalid) do
user
|> cast(params, [:name])
|> cast_attachments(params, [:avatar])
|> validate_required([:name, :avatar])
end
내가 아는 한 배열 / 맵을 직접 사용하는 것은 지원되지 않습니다.
그러나 스키마를 사용하여 맵으로 저장할 수 있습니다.
이것은 작동합니다.
defmodule Image do
use Ecto.Schema
use Arc.Ecto.Schema
import Ecto
import Ecto.Changeset
@required_fields ~w(file)
@optional_fields ~w()
embedded_schema do
field :file, MyApp.UserImage.Type
end
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> cast_attachments(params, [:file])
end
end
defmodule User do
use Ecto.Schema
import Ecto
import Ecto.Changeset
schema "projects" do
field :code, :string
embeds_many :images, MyApp.Image
end
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> cast_embed(:images) # invoke changeset in the embed module
end
end
그런 다음 이렇게 사용할 수 있습니다.
images = [%{file: "image1"}, %{file: "image2"}]
changeset = User.changeset(user, %{"images" => images})
new_user = Repo.update!(changeset)
urls = Enum.map new_user.images, fn image ->
UserImage.urls({image.file, new_user})
end
유일한 단점은 이미지를 저장할 때 더 이상 모듈 에서 scope
매개 변수를 사용할 수 없다는 것 UserImage
입니다. 이는 arc_ecto가 scope
cast_attachments 함수를 호출 할 때 모델을 사용 하고 이제 함수를 호출 할 때 원래 모델 (User) 이 없기 때문 입니다.
마이그레이션 파일에서 이미지 필드를 :map
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다