Phoenix.HTML:为belongs_to关系创建表单元素

时间:2016-04-20 08:49:51

标签: phoenix-framework

鉴于下面的模式

schema "contact" do
  field :name, :string
  field :phone, :string
  belongs_to :address, Db.Address
end

schema "address" do
  field :street, :string
  field :city, :string
  field :state, :string
  field :zip, :string

  has_one :contact, Db.Contact
end

使用Pheonix.HTML我想同时在表单中填写联系人和地址的详细信息,然后在后端使用事务首先插入地址,并将新ID分配给联系人在插入之前记录。我已经找到了Ecto部分,它只是Phoenix.HTML方面,我似乎无法工作。

以下是非工作html.eex代码的摘录。

<%= form_for @changeset, contact_path(@conn, :do_create_contact), fn cnt -> %>
  <div class="form-group">
    <label>Name</label>
    <%= text_input cnt, :name, class: "form-control" %>
  </div>
  <div class="form-group">
    <label>Phone</label>
    <%= text_input cnt, :phone, class: "form-control" %>
  </div>
  <hr/>
  <div class="form-group">
    <label>Address</label>
    <%= inputs_for cnt, :address, fn addr -> %>
      <div>
        <small>Street</small>
        <%= textarea addr, :street, class: "form-control" %>            
        <small>City</small>
        <%= text_input addr, :city, class: "form-control" %>
        <div class="row">
          <div class="col-xs-6">
            <small>State</small>
            <%= text_input addr, :state, class: "form-control" %>
          </div>
          <div class="col-xs-6">
            <small>Zip</small>
            <%= text_input addr, :zip, class: "form-control" %>
          </div>
        </div>
      </div>
    <% end %>
  </div>
<% end %>

我遇到了错误could not generate inputs for :address根本不可能做我想做的事情吗?

1 个答案:

答案 0 :(得分:0)

请在以后的帖子中添加完整的错误消息。 我测试了你的代码片段并得到了同样的错误: (ArgumentError) could not generate inputs for :address from MyApp.Contact. Check the field exists and it is one of embeds_* or has_*

这里的问题是你以错误的方式创建关联。 切换您的belongs_tohas_one。基本模型应该包含has_*字段。

将您的架构更改为:

schema "contact" do
  field :name, :string
  field :phone, :string

  has_one :address, Db.Address
end

schema "address" do
  field :street, :string
  field :city, :string
  field :state, :string
  field :zip, :string

  belongs_to :contact, Db.Contact
end

有关详细信息,请参阅Ecto.Schema hexdocs不要忘记也可以更改您的迁移!