0

今天我意识到,我在 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 有这样的方法还是我应该以其他方式这样做?

回答:

我结合了两个答案:

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
4

2 回答 2

0

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

例子:

1.9.2-p290 :005 > "person".pluralize.to_sym
 => :people
于 2013-08-02T00:41:08.600 回答
0

我想url_for这就是你想要的。

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

于 2013-08-02T00:44:27.077 回答