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

这一生的挚爱 提交于 2019-12-12 04:49:55

问题


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

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.

Please advise. Many thanks.


回答1:


In my State controller:

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

Replace the form with this:

<%= link_to "Add new state", country_states_path(@country), :remote => true, :method => :post %>

I removed the nextState() function, entire form.



来源:https://stackoverflow.com/questions/10107689/getting-rid-of-form-and-use-just-button-to-create-new-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!