摆脱形式,只用按钮创建新记录
问题描述:
Rails 3.1。我有以下几点:摆脱形式,只用按钮创建新记录
// _form.html.erb
<%= form_for ([@country, @state], :remote => true) do |td| %>
<div id= "state_errors" style="display:none"></div>
<%= td.text_field :position, :id => "next_state" %>
<div class="actions">
<%= td.submit %>
</div>
<% end %>
// global.js
function nextState() {
Array.max = function(array) {
return Math.max.apply(Math, array);
};
var getLastState = $("input.sortable_state_item_position").map(function() {
return $(this).val();
}).get();
getLastState.push("0");
return Array.max(getLastState) + 1;
}
$("input#next_state").val(nextState());
// states_controller.rb
class StatesController < ApplicationController
before_filter :load
def load
@country = Country.find(params[:country_id])
@states = State.all
end
def create
@state = @country.states.build(params[:state])
@state.save
end
...
end
你会发现,我创建了一个form
标签用户点击提交按钮时创建一个记录。但我不知道我是否可以摆脱整个form_for
,只是使用正常的a
或button
来触发create
,因为我有点儿觉得整个表格是多余的,因为用户不需要输入任何东西。我的JavaScript自动输入值。
请指教。非常感谢。
答
在我的状态控制器:
def create
@state = @country.states.build(params[:trip_day])
@state.position = State.where(:country_id => @country.id).maximum(:position).to_i + 1
@state.save
end
更换form
本:
<%= link_to "Add new state", country_states_path(@country), :remote => true, :method => :post %>
我删除了nextState()
功能,整个form
。