立即保存多个has_many关联Phoenix 1.3

时间:2018-02-12 12:37:21

标签: elixir phoenix-framework ecto

我有两种模式:

 defmodule TransactionApi.Messages.Event do
  use Ecto.Schema
  import Ecto.Changeset
  alias TransactionApi.Messages.Event
  alias TransactionApi.Messages.EventDetail

  schema "events" do
    field :city, :string
    field :email, :string
    field :ip, :string
    field :sender, :string
    field :status, :string
    field :subject, :string
    field :template, :string
    field :ts, :utc_datetime
    field :uniq_id, :string
    field :user_agent, :string

    has_many :event_details, EventDetail

    timestamps()
  end

  @doc false
  def changeset(%Event{} = event, attrs) do
    event
    |> cast(attrs, [:sender, :uniq_id, :ts, :template, :subject, :email, :status, :ip, :city, :user_agent])
    |> cast_assoc(:event_details)
    |> validate_required([:sender, :uniq_id, :ts, :subject, :email, :status])
  end
end

defmodule TransactionApi.Messages.EventDetail do
  use Ecto.Schema
  import Ecto.Changeset
  alias TransactionApi.Messages.EventDetail
  alias TransactionApi.Messages.Event


  schema "event_details" do
    field :ts, :utc_datetime
    field :url, :string

    belongs_to :event, Event, foreign_key: :event_id
    timestamps()
  end

  @doc false
  def changeset(%EventDetail{} = event_detail, attrs) do
    event_detail
    |> cast(attrs, [:url, :ts, :event_id])
    |> validate_required([:ts, :event_id])
  end
end

我想在我的EventDetail控制器中保存事件及其关联的event

  def create(conn, %{"mandrill_events" => event_params}) do
    params = parse_incoming event_params
    with {:ok, %Event{} = event} <- Messages.create_event(params) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", event_path(conn, :show, event))
      |> render("show.json", event: event)
    end
  end

这就是我构建的params地图的样子:

%{      
  city: "Oklahoma City",
  email: "example.webhook@mandrillapp.com",
  event: "open",
  event_details: [
    %{"ts" => #DateTime<2013-04-04 21:31:51Z>, "url" => "http://mandrill.com"},
    %{"ts" => #DateTime<2013-04-04 21:31:51Z>}
  ],
  ip: "127.0.0.1",
  sender: "example.sender@mandrillapp.com",
  status: "sent",
  subject: "This an example webhook message",
  tags: ["webhook-example"],
  template: nil,
  ts: #DateTime<2018-02-12 12:33:48Z>,
  uniq_id: "exampleaaaaaaaaaaaaaaaaaaaaaaaaa",
  user_agent: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.8) Gecko/20100317 Postbox/1.1.3"
}

但我的api会返回错误: {"errors":{"event_details":[{"event_id":["can't be blank"]},{"event_id":["can't be blank"]}]}}

如何通过对EventDetail表的foreign_key引用确保关联的Event被正确保留,&#34;最佳做法&#34;接近这里?

修改

在Phoenix 1.3中,似乎他们已经在模型的上下文中添加了create_[table_name]并处理了changeset和插入(我认为这种变化伴随着想要分离网络应用程序的相关部分,但不确定):

  def create_event(attrs \\ %{}) do
    %Event{}
    |> Event.changeset(attrs)
    |> Repo.insert()
  end

1 个答案:

答案 0 :(得分:1)

我想出了一种保存包含嵌套关联的地图的方法,但由于我是Phoenix和Elixir的新手(一般的函数式编程),我不确定这是正确/最佳实践方法。< / p>

public class ViewHolder extends RecyclerView.ViewHolder {
TextView product_name;

ViewHolder(View itemView) {
    super(itemView);
    product_name = (TextView) itemView.findViewById(R.id.product_name);
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int itemPosition = getLayoutPosition();
            Toast.makeText(getApplicationContext(), itemPosition + ":" + String.valueOf(product_name.getText()), Toast.LENGTH_SHORT).show();
        }
    });
}
}

event_controller.ex

%{      
  city: "Oklahoma City",
  email: "example.webhook@mandrillapp.com",
  event: "open",
  event_details: [
    %{"ts" => #DateTime<2013-04-04 21:31:51Z>, "url" => "http://mandrill.com"},
    %{"ts" => #DateTime<2013-04-04 21:31:51Z>}
  ],
  ip: "127.0.0.1",
  sender: "example.sender@mandrillapp.com",
  status: "sent",
  subject: "This an example webhook message",
  tags: ["webhook-example"],
  template: nil,
  ts: #DateTime<2018-02-12 12:33:48Z>,
  uniq_id: "exampleaaaaaaaaaaaaaaaaaaaaaaaaa",
  user_agent: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.8) Gecko/20100317 Postbox/1.1.3"
}

然后在我的 def create(conn, %{"mandrill_events" => event_params}) do params = parse_incoming event_params with {:ok, %Event{} = event} <- Messages.create_event(params) do event |> Messages.add_event_details(params[:event_details]) conn |> put_status(:created) |> put_resp_header("location", event_path(conn, :show, event)) |> render("show.json", event: event) end end 上下文中:

Message