加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 动态获取路径路径

发布时间:2020-12-17 03:28:40 所属栏目:百科 来源:网络整理
导读:我最近将一些模板从ERB转换为Haml.它大多变得更清洁,更好,但按钮定义开始变得很糟糕. 我想转换它 = link_to t('.new',:default = t("helpers.links.new")),new_intern_path,:class = 'btn btn-primary' if can? :create,Intern 这样的事情 = new_button Inte
我最近将一些模板从ERB转换为Haml.它大多变得更清洁,更好,但按钮定义开始变得很糟糕.

我想转换它

= link_to t('.new',:default => t("helpers.links.new")),new_intern_path,:class => 'btn btn-primary' if can? :create,Intern

这样的事情

= new_button Intern

除了实习生,我还有其他几个实体,所以其他所有页面也会从中受益.

所以,我输入了这段代码

def new_button(person_class)
    return unless can?(:create,person_class)

    new_route_method = eval("new_#{person_class.name.tableize}_path")

    link_to t('.new',new_route_method,:class => 'btn btn-primary'
  end

它按预期工作.我只是不确定那个eval电话(因为它是邪恶的,所有这一切).有一种更简单,更不邪恶的方式吗?

解决方法

您可能有兴趣看一下PolymorphicRoutes( http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html#method-i-polymorphic_path).

有了它,您的代码可能看起来像:

def edit_button(person)
  return unless can?(:edit,person)

  link_to t('.edit',:default => t("helpers.links.edit")),edit_polymorphic_path(person),:class => 'btn btn-mini'
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读