2016-08-23 48 views
9

我在如何實際設置與變更集的關聯方面存在困難。我有這樣的代碼在我的模型:Elixir Ecto:如何在變更集中設置belongs_to關聯

defmodule MyApp.MemberApplication do 
    use MyApp.Web, :model 
    use Ecto.Schema 
    use Arc.Ecto.Schema 

    alias MyApp.Repo 
    alias MyApp.MemberApplication 

    schema "applications" do 
    field :name, :string 
    field :email, :string 
    field :time_accepted, Ecto.DateTime 
    field :time_declined, Ecto.DateTime 
    belongs_to :accepted_by, MyApp.Admin 
    belongs_to :declined_by, MyApp.Admin 

    timestamps() 
    end 

    def set_accepted_changeset(struct, params \\ %{}) do 
    struct 
    |> cast(params, [:time_accepted, :accepted_by_id]) 
    |> cast_assoc(params, :accepted_by) 
    |> set_time_accepted 
    end 

    defp set_time_accepted(changeset) do 
    datetime = :calendar.universal_time() |> Ecto.DateTime.from_erl 
    put_change(changeset, :time_accepted, datetime) 
    end 
end 

我要救關聯到執行特定操作(接受或拒絕的member_application)的Admin和時間戳。時間戳的生成工作,但是當我嘗試保存的關聯,我總是得到錯誤

** (FunctionClauseError) no function clause matching in Ecto.Changeset.cast_assoc/3 

這是我要如何設置的關聯:

iex(26)> application = Repo.get(MemberApplication, 10) 
iex(27)> admin = Repo.get(Admin, 16) 
iex(28)> changeset = MemberApplication.set_accepted_changeset(application, %{accepted_by: admin}) 
+7

嘗試'Application.set_accepted_changeset(應用程序,%{accepted_by_id:admin.id})'和'|> cast_assoc(:accepted_by)'。 – Dogbert

+0

這工作。將寫下一個答案 –

回答

7

感謝@Dogbert。這是我如何得到它的工作

defmodule MyApp.MemberApplication do 
    use MyApp.Web, :model 
    use Ecto.Schema 
    use Arc.Ecto.Schema 

    alias MyApp.Repo 
    alias MyApp.MemberApplication 

    schema "applications" do 
    field :name, :string 
    field :email, :string 
    field :time_accepted, Ecto.DateTime 
    field :time_declined, Ecto.DateTime 
    belongs_to :accepted_by, MyApp.Admin 
    belongs_to :declined_by, MyApp.Admin 

    timestamps() 
    end 

    def set_accepted_changeset(struct, params \\ %{}) do 
    struct 
    |> cast(params, [:time_accepted, :accepted_by_id]) 
    # Change cast_assoc 
    |> cast_assoc(:accepted_by) 
    |> set_time_accepted 
    end 

    defp set_time_accepted(changeset) do 
    datetime = :calendar.universal_time() |> Ecto.DateTime.from_erl 
    put_change(changeset, :time_accepted, datetime) 
    end 
end 

然後預加載關聯並直接設置ID。或者在查詢直接做到這一點:

iex(26)> application = Repo.get(MemberApplication, 10) 
iex(27)> application = Repo.preload(application, :accepted_by) 
iex(28)> admin = Repo.get(Admin, 16) 
iex(29)> changeset = MemberApplication.set_accepted_changeset(application, %{accepted_by_id: admin.id}) 
+0

你應該接受你自己的答案,所以這顯示爲有一個解決方案。 – kioopi