Shalafister's
Shalafister's

Reputation: 889

Send data with button from another action

I would like to send a data to update action from new action with a button. So if user clicks to cancel button;

<%= button_to "Cancel", {:controller => :requests,
        :action => 'update', :user_id =>received.user.id, :id => received.id }, :value => "Cancelled" %>


The value has to be sent to the `update` action. But instead I receive an error;

 Started POST "/user/295/requests/29" for ::1 at 2015-10-17 12:35:30 +0300

ActionController::RoutingError (No route matches [POST] "/boats/295/requests/29"):

and the request controller;

def update
     @request = Request.find(params[:id])
     puts situation = params[:situation]
     if @request.update_attributes(situation)
      flash[:success] = "Approved"
      redirect_to new_user_request(current_user.id)
    else
      redirect_to new_user_request(current_user.id)
    end

Basically, would like to send a text data to update action in requests controller.

Upvotes: 2

Views: 991

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

Arup's answer will get the button_to working for you.

To give you some code, you'll need the following:

<%= button_to "Cancelled", requests_path(received.id, received.user.id), method: :put %>

In regards the code itself, you'd be better off doing this:

<%= button_to "Cancelled", requests_path(received.id, received.user.id), method: :put, {params: {situation: "Cancelled"}} %>

#app/controllers/situations_controller.rb
class SituationsController < ApplicationController
   def update
      @situation = Situation.find params[:id]
      @situation.update situation_params
   end

   private

   def situation_params
      params.require(:situation).permit(:situation)
   end
end

This will allow you to update the @situation to have a "situation" of "cancelled".

I would recommend several fixes:

  1. You should rename your "situation" column to status (so you can call @situation.status

  2. You should make your status column less dependent on text -- it should have a rigid spec, maybe make it boolean or something. This will allow you to call something like @situation.active?

  3. You should always use the Rails path helpers wherever you can. Sending a hash of controller/action information is fine, but it's best to use the inbuilt paths for better convention

Upvotes: 1

Related Questions