将助手链接到所有控制器的操作

时间:2013-08-02 00:30:21

标签: ruby-on-rails ruby

今天我意识到,我在5个不同的视图中有这样的链接

<%= link_to t(:edit, scope: [:admin, :actions :model_name]), edit_admin_model_name_path(model_name)), class: "icon-edit" %>
<%= link_to t(:delete, scope: [:admin, :actions :model_name]), admin_model_name_path(model_name)),method: :delete, class: "icon-edit", data: { confirm: t(:confirm, scope: [:admin, :confirmation, eval(":#{model}s")]) %>

我的代码看起来非常糟糕。所以我想为这样的链接创建一个帮助方法。我想,它应该是这样的:

  def link_to_edit(model)
    link_to t(:edit, scope: [:admin, :actions :model_name]), edit_admin_METHOD_I_NEED(model)_path(METHOD_I_NEED(model)), class: "icon-edit"
  end
  def link_to_delete(model)
    link_to t(:delete, scope: [:admin, :actions :model_name]), admin_METHOD_I_NEED(model)_path(METHOD_I_NEED(model))), method: :delete, class: "icon-delete", data: { confirm: t(:confirm, scope: [:admin, :confirmation, ":#{model}s"]) }
  end

所以,我需要的是与#{}相对的ruby方法。

Ruby有这样的方法还是我应该以其他方式做到这一点?

解答:

我结合了两个答案:

def link_to_delete(model) 
  link_to t(:delete, scope: [:admin, :actions, model.pluralize.to_sym]), url_for(controller: model.pluralize.to_sym,...), method: :delete, class: "icon-delete", data: { confirm: t(:confirm, scope: [:admin, :confirmation, model.pluralize.to_sym) } 
end

2 个答案:

答案 0 :(得分:0)

为什么不model.pluralize.to_sym而不是":#{model}s"

示例:

1.9.2-p290 :005 > "person".pluralize.to_sym
 => :people

答案 1 :(得分:0)

我认为url_for就是你想要的。

看看: http://apidock.com/rails/ActionDispatch/Routing/UrlFor/url_for