Search code examples
ruby-on-railsrubyformtastic

Button: Create one object, then redirect to create another?


railsnoobquestion: I am trying to develop a feature where a user can save an object in rails and is then forwarded to the form again, to create another object.

I could think of two options: -Create a fully new route -Add data to the restaurant post object, check for that data in the controller?

Has anyone built a similar feature?

thx


Solution

  • The solution was to create a hidden form field with another submit button:

    %input#create_another{:name => "create_another", :type => "hidden", :value => 0 }
    %a.btn.btn-info#submit_another
    

    Then use javascript to submit the form:

    jQuery(document).ready(function() {
      $("#submit_another").click(function() {
        $('#create_another').attr('value','1');
        console.log($('#create_another').attr('value'));
        $(".formtastic").submit();
        return true;
      });
    });
    

    Inside the respective controller, in my case, category controller:

    if params[:create_another].nil?
      @create_another = false
    else
      @create_another = (params[:create_another] == "1")
    end
    respond_to do |format|
      if @category.save
        if @create_another
          format.html { redirect_to new_restaurant_category_path(@restaurant), notice: I18n.t(:entry_successfully_created, :name => I18n.t(:category_singular)) }