摆脱表格并仅使用按钮来创建新记录 [英] Getting rid of form and use just button to create new record

查看:101
本文介绍了摆脱表格并仅使用按钮来创建新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 3.1.我有以下内容:

Rails 3.1. I have the following:

// _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自动输入值.

You will notice that I created a form tag for user to create a record when the submit button is clicked. But I am not sure if I could get rid of the entire form_for and just use a normal a or button to trigger the create because I kinda thing that the entire form is redundant as there is no need for the user to input anything. My javascript enters the value automatically.

请告知.非常感谢.

推荐答案

在我的状态控制器中:

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.

这篇关于摆脱表格并仅使用按钮来创建新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆