摆脱形式,仅使用按钮创建新记录

Getting rid of form and use just button to create new record

本文关键字:按钮 创建 新记录      更新时间:2023-09-26

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,只使用正常的abutton来触发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.