Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign custom function to formtastic action?

My form:

<%= semantic_form_for(@campaign) do |f| %>
...
  <%= f.actions do %>
    <%= f.action :submit, label: "Save"%>
    <%= f.action :submit, label: "Save & New" %>
    <%= f.action :cancel, label: "Cancel"%>
  <% end %>
<% end %>

Function in campaign_controller.rb:

  def save_and_new
    print 'SAVE_AND_NEW'
    @campaign = Campaign.find(params[:id])

    respond_to do |format|
      if @campaign.update_attributes(params[:campaign])
        format.html { redirect_to new_campaign_path, notice: 'Campaign was successfully usaved.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @campaign.errors, status: :unprocessable_entity }
      end
    end
  end

Routes.rb:

  resources :campaigns do 
    member do
      post 'save_and_new'
    end
  end

Route, according to the function:

save_and_new_campaign POST   /campaigns/:id/save_and_new(.:format) campaigns#save_and_new

And the only thing, that I don't understand, is what to write in action to call the function.

like image 363
Alex Teut Avatar asked Nov 04 '22 01:11

Alex Teut


1 Answers

I'm not sure what exactly you are trying to do with the save_and_new action, but I can tell you why you aren't triggering it.

By default, the form you are creating with formtastic using the semantic_form_for is going to use the RESTful convention of hitting the create action for a new record and the update action for an existing record. If you are successfully hitting the create/update actions with your first submit button (labeled "Save"), but you want your second, "Save & New" button to do something different, you will need to check the value of params[:commit] in the controller to fork your handling of the submissions. Perhaps some code would be more clear. Let's say you are making a submission to update an existing record:

def create
  if params[:commit] == "Save"
    # code for handling "Save" scenario
  else
    # code for handling "Save & New" scenario, perhaps even directly call:
    save_and_new
  end
end


def update
  if params[:commit] == "Save"
    # code for handling "Save" scenario
  else
    # code for handling "Save & New" scenario, perhaps even directly call:
    save_and_new
  end
end

Again, I'm not clear on what you are trying to accomplish with the save_and_new action, and questioning that assumption may set you down the path to a better design, but to answer your immediate question: checking the value of params[:commit] in create or update should set you on the right track.

like image 154
Cade Avatar answered Nov 15 '22 05:11

Cade