使用link_to按钮在2个不同的控制器上调用操作

时间:2013-04-05 15:41:42

标签: ruby-on-rails

我想用link_to按钮调用2个不同的动作。当我放置以下代码时,按钮仅显示为蓝色链接,并且不调用第二个操作。有没有人知道解决这个问题的策略?

<%= link_to "Remove from Cabinet", { :controller => 'devices', :action => 'detach_device_from_cabinet', :id => device.id }, 
            { :controller => 'cabinets', :action => 'unmark_validated', :id => @cabinet.id }, :class => "btn btn-danger", :confirm => "Detach Device: are you sure?" %>

感谢。

3 个答案:

答案 0 :(得分:5)

从单个link_to调用多个控制器操作不是一个好习惯。你为视图添加了太多的逻辑。

有一种称为“胖模型,瘦模控制器”的导轨设计模式。您希望在模型中完成所有业务逻辑,并且控制器只需调用模型的方法。在此特定示例中,您希望从机柜中分离设备,并且每个设备可以位于一个机柜上,并且每个机柜可以容纳多个设备。

我没有检查过这段代码,但它应该接近你想要的:

cabinet.rb

class Cabinet < ActiveRecord::Base
  has_many :devices
  ...

  def self.detach_device(id)
    cabinet = Cabinet.where(device: id).first
    cabinet.devices.drop(id)
    cabinet.unmark_validated
  end

  def unmark_validated
     cabinet.marked == false
  end
end

device.rb

class Device < ActiveRecord::Base
  belongs_to :cabinet
  ...

end

cabinets_controller.rb

class CabinetsController < ApplicationController
  def detach_from_cabinet
    @cabinet = Cabinet.detach_device(params[id])

  end
end

<%= link_to "Remove from Cabinet", :controller => 'cabinets', :action => 'detach_device', id => device.id %>

答案 1 :(得分:0)

我以前从来没有这样,我没有得到逻辑,但你应该进行重构...调用一个动作,发送数据,并且该动作可以调用一个函数来执行你想要做的其他事情。此外,您应该使用别名,在路线中定义它。

答案 2 :(得分:0)

出现类似情况我需要用户在一个模型视图中按下按钮并在不同模型的控制器中创建一个新行,然后同时更改源模型中的布尔属性。我最终变薄了控制器,并在相应的模型中创建了一个新方法,并在操作中指向它。捎带@John的答案,这里对我有用,可能是你或任何需要在一个用户按下按钮时执行多个操作的人的替代策略,可能在多个模型之间:

FOO CONTROLLER / NEW

 def new
    ...
    # After button is pushed sending params to this action, thusly 
    # creating the new row, and saving it 
    @foo.save
    # Then to the newly created method
    @foo.new_method 
    # and back for a redirect
    redirect_to :foos, notice: "..."
  end

foo.rb

  def new_method
    @bar = Bar.find_by(:attribute => true)
    # Simply need to fllip attribute from true to false
    if @bar.attribute == true
      @bar.attribute = false
    end
    @bar.save
  end
相关问题