15

私は次のモデルを持っています:

# Foo model
schema "foo" do
  field :name, :string
  has_many: :bars, App.Bar
end

# App model
schema "bar" do
  field :name, :string
  belongs_to: foo, App.Foo
end

そして、このフォーム:

# form.html (Foo)
<%= form_for @changeset, @action, fn f -> %>
  <%= text_input f, :name, class: "form-control" %>
  <%= submit "Submit", class: "btn btn-primary" %>
<% end %>

Fooこのフォーム内で、テキスト フィールドを追加して新しいフォームに入力するにはどうすればよいBarsですか?

barsプリロードされていないため、次は機能しません。

<%= text_input f, :bars, class: "form-control" %>

私は正しい軌道に乗っていますか?Barsもしそうなら、どうすればフォームにプリロードできますか?

更新、コントローラ:

def new(conn, _params) do
  changeset = %Foo{} |> Repo.preload(:bars) |> Foo.changeset
  render(conn, "new.html", changeset: changeset)
end

def create(conn, %{"foo" => foo_params}) do
  changeset = %Foo{} |> Repo.preload(:bars) |> Foo.changeset(foo_params)

  if changeset.valid? do
    Repo.insert!(changeset)

    conn
    |> put_flash(:info, "Foo created successfully.")
    |> redirect(to: foo_path(conn, :index))
  else
    render(conn, "new.html", changeset: changeset)
  end
end

プリロードは機能しているようですが、Argument error到達 すると次のようになり<%= text_input f, :bars, class: "form-control" %>ます。

[error] #PID<0.280.0> running App.Endpoint terminated
Server: 192.168.48.202:4000 (http)
Request: GET /
** (exit) an exception was raised:
    ** (ArgumentError) argument error
        :erlang.bit_size([])
        (phoenix_html) lib/phoenix_html/tag.ex:66: anonymous fn/2 in Phoenix.HTML.Tag.tag_attrs/1
        (elixir) lib/enum.ex:1261: Enum."-reduce/3-lists^foldl/2-0-"/3
        (phoenix_html) lib/phoenix_html/tag.ex:35: Phoenix.HTML.Tag.tag/2
        (app) web/templates/foo/form.html.eex:16: anonymous fn/1 in App.FooView.form.html/1
        (phoenix_html) lib/phoenix_html/form.ex:181: Phoenix.HTML.Form.form_for/4
        (app) web/templates/foo/form.html.eex:1: App.FooView."form.html"/1
        (app) web/templates/foo/new.html.eex:3: App.FooView."new.html"/1
4

2 に答える 2

2

モデルにネストされた関連付けがある場合、inputs_forを使用してネストされたデータをフォームに添付できます。たとえば、ネストされた入力セクションのこちらを参照してください。

于 2015-09-10T15:27:04.743 に答える