ruby-on-rails – 确定操作是在成员上还是在集合上
我一直试图找到一种干净的方法来确定一个动作(在轨道控制器中)适用于成员或收集.
例如,当您在routes.rb中声明时 resources :projects 您将获得“在集合上”定义的以下方法: >指数 以及在“成员”上定义: >更新 我试图找到一种方法来在视图中利用这个伟大的模式,例如: <% if @controller.action.applies_on_members? %> <%= link_to :destroy,:method => "delete",:confirm => "RU Sure" %> <%= link_to :show,"show" %> <% end %> 同样,这在before_filters中也很有用 before_filter :find_project,:only_on_members => true 目前我必须做以下事情: before_filter :find_project,:except => [:new,:create,:index,:export_all,:destroy_all,:archive_all] 这非常令人讨厌,我的想法是所有这些行为都有一个共同的行为:它们是在集合上定义的. 有没有人知道如何以干净的方式实现这一目标? 注意:我问这个问题的原因是因为我正在寻找可扩展的开发方面的东西,这样,新的自定义操作会自动继承before_filters或某些partials的行为. 谁从来没有写下类似的东西 <% unless ["new","index","some_other_action1","some_other_action2","some_other_action3","some_other_action4"].include? @controller.action_name %> <%= link_to "Destroy",:project,:method => :delete %> <% end %> 解决方法
在发布这个问题差不多一年后,我知道找到了一个合理的解决方案.
如果我们看一下on => :member和on => :收藏真的很好,差别基本就是on => :member生成一个包含:id param的路径,而on => :集合版本没有. 然后,一个简单的解决方案是在自定义方法中测试params [:id]是否为空.它看起来像这样(比如在application_controller.rb中): class ApplicationController < ActionController::Base def on_member? !params[:id].blank? end helper_method :on_member? #method will be accessible in views end 例如,如this post所述,我们可以在before_filter中执行类似的操作: before_filter :find_project,:if => :on_member? 在视图中,这允许我检查方法的类型如下: <% if on_member? %> <%= link_to :destroy,"show" %> <% end %> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |