Ruby link_to 方法的小瑕疵

lhy20062008 · 2014年09月15日 · 最后由 lhy20062008 回复于 2014年09月17日 · 2327 次阅读

今天在做项目的时候,发现 link_to 对传入 nil 和""参数的处理不同。 假设当前页面路径为'admin/test' 那么,当参数为 nil 时,得到的结果为: <%= link_to nil, nil %> admin/test

当参数为""时, <%= link_to '', '' %>

另看 rails 相关源码,对于可能出现 nil 的情况,可以使用以下方式: <%= link_to_if(condition, name, url) %> 当 condition 为 true,才生成一个 a 标签

追加: 当使用 link_to_if 方法时候,一定要慎用,不然会出问题,比如: <%= link_to_if(post.source.present? post.source.name, admin_post_source_path(post.source) %> 当 post.source 为 nil 时,会继续执行 post.source.name 代码,此时就会报 no method 错误。

原来还有方法叫 link_to_if 的啊

#2 楼 @zhbinx 是啊,但是这个方法设计得不是很好。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号