简体   繁体   English

在Rails的同一控制器内调用动作

[英]Calling an action within the same controller in Rails

The following works, but I am wondering if there is a better way? 以下作品有效,但我想知道是否有更好的方法? On a index page we are listing widgets. 在索引页面上,我们列出了小部件。 You can edit each widget in its show view, but to increase efficiency we would like to give users the ability to do bulk actions from the index page by adding a check box to each widget, then gather up the selected widgets, pass those along to the controller and 'do stuff' to them from the controller in one fail swoop. 您可以在其显示视图中编辑每个窗口小部件,但是为了提高效率,我们希望通过向每个窗口小部件添加一个复选框,然后收集选定的窗口小部件,并将其传递给用户,来从索引页面执行批量操作。控制器,然后一次失败地从控制器“执行任务”。 Here is the code... 这是代码...

view 视图

<%= form_tag bulk_change_widgets_path(method: :post) do %>  
      <%- @widgets.each do |image| -%>
        ....
              <%= check_box_tag 'selected_widget_ids[]', widget.id -%>
          </td>
        </tr>
      <%- end -%>
      <%= submit_tag %> 
    <%- end -%>

controller 控制者

action_one
  @widget = Widget.find(params[:id])
...
end

action_two
  @widget = Widget.find(params[:id])
...
end

def bulk_change_widgets
    selected_widgets = params[:selected_widget_ids]

    selected_widgets.each do |widget|
      params[:id] = widget
      action_one
      action_tow
    end

    redirect_to widgets_path
  end

The existing structure of action_one/two needs to stay in place to accommodate the instance methods called from the show page for each widget. action_one / two的现有结构需要保留在原处,以容纳从显示页面调用的每个小部件的实例方法。 However, something doesn't feel right about calling action_one/two this way from within the same controller. 然而,有些东西感觉不对有关从同一个控制器内调用action_one /两这种方式。 Is there a better, or a Rails Way to do this? 是否有更好的方法或Rails方式可以做到这一点?

This could be more efficient. 这可能会更有效率。 Instead of multiple queries to get widgets individually, do a single query to get them all and use this list to iterate. 而不是通过多个查询来单独获取小部件,而是通过单个查询将它们全部获取并使用此列表进行迭代。 If it's too many widget ids and loading them in memory is an issue (I don't think this is the case), you can do a find_each 如果有太多的小部件ID并将它们加载到内存中是个问题(我不认为是这种情况),则可以执行find_each

  def bulk_change_widgets
    selected_widgets = Widget.where(:id => params[:selected_widget_ids])

    selected_widgets.each do |widget|
      widget.take_action
    end

    redirect_to widgets_path
  end

And, like the comments said, move the method to the Widget class (fat models, thin controllers). 并且,如评论所述,将方法移至Widget类(胖模型,瘦控制器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM