如何从视图中将变量传递给控制器​​操作?

时间:2013-07-03 19:12:23

标签: ruby-on-rails

视图/辆/ _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

3 个答案:

答案 0 :(得分:3)

为了简化并以Rails方式,您可以使用Rails resources

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

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

答案 1 :(得分: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>

答案 2 :(得分:0)

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

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