我试图使用模态(来自物化)将对象添加到我的数据库。当用户点击" new"按钮,将显示模态,填写表格后,将创建对象。
主视图看起来像这样
.
.
.
<%= 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>
当用户填写模态表单并单击“提交”时,将在items_controller中调用create动作
def create
@item = Item.new(params[:item])
respond_to do |format|
if @item.save
format.js
else
format.js
end
end
end
我在提交后看了一下params散列,看来输入到表单中的值没有被发送到create动作。我检查了输入字段,它们似乎连接到对象
<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)
答案 0 :(得分:3)
您需要在表单中添加一个submit
按钮,当前按钮会创建一个没有数据的自己的表单。
尝试将button_to
转换为f.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>