Getting rid of form and use just button to create

2019-09-11 23:52发布

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条回答
倾城 Initia
2楼-- · 2019-09-12 00:21

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.

查看更多
登录 后发表回答