在导轨中使用模态创建对象



我正在尝试使用模态(从材料化(将对象添加到我的数据库中。当用户单击"新"按钮时,将显示模式,并在填写表单后,将创建对象。

主视图看起来像

.
.
.
<%= link_to "add", new_item_path, remote: true %>
.
. 
.
<div id="addItemModal" class="modal">
  <div class="modal-content">
    <h4 class="col s12">Add Item</h4>
    <div class="row">
      <%= form_with(model: Item.new, class: "col s12") do |f| %>
        <div class="row">
          <div class="input-field col s6">
            <%= f.label :name %>
            <%= f.text_field :name, class: "validate" %>
          </div>
        </div>
      <% end %>
    </div>
  </div>
  <div class="modal-footer">
    <a href="#!" class="modal-action modal-close waves-effect waves-
         green btn-flat">Cancel</a>
    <%= button_to "Save",
        items_path,
        class: "modal-action modal-close waves-effect waves-green btn 
        light-blue darken-2 text-white", remote: true %>
  </div>
</div>

当用户填写模式表格并单击提交时,在the itemp_controller

中调用创建操作
def create
  @item = Item.new(params[:item])
  respond_to do |format|
    if @item.save
      format.js
    else
      format.js
    end
  end
end

我看了提交后的参数哈希,看来输入到表单中的值并未发送到创建操作。我检查了输入字段,它们似乎已连接到对象

<input class="validate" type="text" name="item[name]">

编辑:

服务器响应

Started POST "/items" for 127.0.0.1 at 2017-06-26 17:59:23 -0500
Processing by ItemsController#create as JS
Parameters {"authenticity_token"=>"B1YVBtBy0NGe0jnhdeJquj19g8aJa8WfNwA/k8vekOySACiJ20wnR5XAI2rw7mIIUSnp5K7ZqmLxYdddGqimvw=="}
 (0.1ms)  begin transaction
 (0.1ms)  rollback transaction
Redirected to http://localhost:3000/?message=Error+Saving
Completed 200 OK in 3ms (ActiveRecord: 0.1ms)

您需要在表单上添加submit按钮,您当前的按钮创建了自己的形式,没有数据。

尝试button_tof.submit,并确保将其包括在form_with块中:

<div id="addItemModal" class="modal">
  <%= form_with(model: Item.new, class: "col s12") do |f| %>
    <div class="modal-content">
      <h4 class="col s12">Add Item</h4>
      <div class="row">
        <div class="row">
          <div class="input-field col s6">
            <%= f.label :name %>
            <%= f.text_field :name, class: "validate" %>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-footer">
      <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat">Cancel</a>
      <%= f.submit "Save", class: "modal-action modal-close waves-effect waves-green btn light-blue darken-2 text-white" %>
    </div>
 <% end %>
</div>

最新更新