从ecto用户中为belongs_to关联选择框

时间:2016-10-28 19:07:37

标签: forms phoenix-framework ecto belongs-to

来自rails的Noob尝试构建具有ecto belongs_to关系的表单。如何将users变量添加到available assigns

控制器:

  def new(conn, params) do
    changeset = Project.changeset(%Project{})
    users = Repo.all(from(u in User, order_by: u.email, select: {u.email, u.id}))
    Logger.debug "Controller: #{inspect users}"
    render(conn, "new.html", changeset: changeset, users: users)
  end

形式:

<%= form_for @changeset, @action, @users, fn f -> %>   
  <div class="form-group">
    <%= label f, :user_id, class: "control-label" %>
    <%= Logger.debug "View 2: #{inspect @users}" %>
    <%= select f, :user_id, @users, class: "form-control" %>
    <%= error_tag f, :user_id %>
  </div>

错误讯息:

(ArgumentError) assign @users not available in eex template.

Available assigns: [:action, :changeset]

很好,我尝试将用户添加到available assigns

1 个答案:

答案 0 :(得分:0)

DERP。这在轨道上也不是正确的。我必须将变量添加到new.html.eex

<h2>New project</h2>

<%= render "form.html", changeset: @changeset,
                        action: project_path(@conn, :create),
                        users: @users %>

<%= link "Back", to: project_path(@conn, :index) %>