0

意见/车辆/_form.html.haml

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

我想在上面的 link_to 中传递@vehicle。我该怎么做呢?

控制器/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
4

3 回答 3

3

为了让它变得简单并且以 Rails 的方式,你可以使用 Rails resources

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

# view:
= link_to 'Deactivate', deactivate_vehicle_path(@vehicle), method: :put
于 2013-07-03T19:19:09.443 回答
1

Marek Lipka 已经给出了最佳答案。还有一种使用方法ajax

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

放一些脚本:

<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>
于 2013-07-03T20:05:58.533 回答
0

这对我有用,我最终在我的控制器中使用了更新操作。

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

于 2013-07-05T16:22:31.447 回答