都知道的, 在 Rails 的 View 里边渲染集合的时候, 会用到 render 方法参数的 collection 选项

1
<%= render partial: "product", collection: @products %>

而不是遍历集合来渲染单个模板.

渲染集合还有个简写形式. 假设 @productsproduct 实例集合, 在 index.html.erb中可以直接写成下面的形式, 得到的结果是一样的:

1
<%= render @products %>

这里, Rails 做的魔法其实是去找遍历成员的 to_partial_path

action_view/renderer/partial_renderer (Rails 4.2)

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def partial_path(object = @object)
object = object.to_model if object.大专栏  Rails render collection 的魔法"n">respond_to?(:to_model) path = if object.respond_to?(:to_partial_path)
object.to_partial_path
else
raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.")
end if @view.prefix_partial_path_with_controller_namespace
prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup)
else
path
end
end

打开 rails console 可以试试

1
2
[1] pry(main)> User.new.to_partial_path
=> "users/user"

这里也可以把 user 这个 model 的 to_partial_path 重写, 返回表示渲染路径的字符串,

如果你的某个 PORO 实现了 to_partial_path, 那对应的 collection 也可以直接用类似的方式去 render

最新文章

  1. VS2010 中,windows服务不能添加 System.Web 引用
  2. Yii的学习(2)--数据访问对象 (DAO)
  3. bzoj 1001
  4. pkg-config问题:
  5. Sql Server 常用自定义函数
  6. 问题:关于坛友的一个js轮播效果的实现
  7. bash shell——与if条件相关的参数意义
  8. Oracle中使用profile管理用户口令
  9. Wix学习整理(4)——关于WiX文件格式和案例HelloWorld的分析
  10. Magicodes.WeiChat——使用OAuth 2.0获取微信用户信息
  11. vue 2.0 + ElementUI构建树形表格
  12. docker上配置mysql主从复制
  13. svn 安装
  14. js零碎知识汇总
  15. Python爬虫之正则表达式的使用(三)
  16. linux固定ip地址
  17. 管理idea Open Recent
  18. DOM-访问元素
  19. 70. Climbing Stairs(动态规划 爬台阶,一次只能爬1,2两节)
  20. ip段/数字,如192.168.0.1/24的意思是什么?(转)

热门文章

  1. 【Vue中的坑】Vue中的@mouseenter没反应?
  2. Java enum应用小结
  3. [NOIP2009普及]分数线划定 T2 排序
  4. 如何写好一个完整的Essay写作论证
  5. PAT Advanced 1076 Forwards on Weibo (30) [图的遍历,BFS,DFS]
  6. [ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war
  7. 获取网站IP地址(Linux,C)
  8. VS2013 MFC opencv 播放视频
  9. 洛谷 P1709 隐藏口令
  10. eclipse中tomcat添加或移除web项目出错,显示无资源能被添加或移除