今天我意识到,我在 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