Bruno
Bruno

Reputation: 6469

How to pass variable into controller action from view?

views/vehicles/_form.html.haml

= link_to "Deactivate", "/vehicles/deactivate"

I want to pass in @vehicle in my link_to above. How do I do this?

controllers/vehicles_controller.rb

  def deactivate
    @vehicle = Vehicle.find(params[:id])
    @vehicle.active = 0
    @vehicle.save

    respond_to do |format|
      format.html { redirect_to vehicles_url }
      format.json { head :no_content }
    end
  end

Upvotes: 0

Views: 182

Answers (3)

Bruno
Bruno

Reputation: 6469

This worked for me, I ended up using the Update action in my controller.

= link_to "Deactivate", vehicle_path(@vehicle, :vehicle => {:active => 0}), method: :put, :class=>'btn btn-mini'

Upvotes: 0

rony36
rony36

Reputation: 3339

Best answer already given by Marek Lipka. There is also a way using ajax

<%= link_to 'Deactivate', javascript::void(0), :class => "deactivate" %>

Put some script:

<script>
$(".deactivate").click(function() {
   $.ajax({
        type: "post",
        url: "/vehicles/deactivate",
        data: {id: <%= @vehicle.id %>},
        dataType:'script',
            beforeSend: function(){
                // do whatever you want
            },
            success: function(response){
                // do whatever you want
            }
        });
});
</script>

Upvotes: 1

Marek Lipka
Marek Lipka

Reputation: 51191

To make it easy and in Rails way, you can use Rails resources:

# routes.rb
resources :vehicles do
  put 'deactivate', on: :member
end

# view:
= link_to 'Deactivate', deactivate_vehicle_path(@vehicle), method: :put

Upvotes: 3

Related Questions