用于创建视图的 ruby 助手围绕关联的文字
我不确定这叫什么,但我有一个模型 a,其中有多个 b。在视图中显示某些模型 a 时,我想打印一些描述它具有的所有模型 b 关联的文本,如下所示:
关联
“与 foo、bar、baz 和 ## more...” foo、bar , baz 是三个 mobdel b 的名称。如果名称超过 3 个,我不想打印所有名称,因此我想用剩余的关联数来尾随它。
我可以在 ruby 中以编程方式执行此操作,但我想知道是否存在一些辅助方法可以为我执行此操作..
谢谢。
I am not sure what this is called, but I have a model a which has_many b. When showing some model a in a view, I would like to print some text describing all the model b associations it has like the following:
"Has an association with foo, bar, baz, and ## more..."
foo, bar, baz are names of three mobdel b's. And I don't want to print all the names if there are more than 3, so I want to trail it off with the balance # of associations remaining.
I can do this programatically in ruby, but I was wondering if some helper methods exists which can do this for me..
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
具有范围检查的版本 + 将项目转换为字符串的可选块:
测试运行:
输出:
Version with range checking + optional block to convert items to string:
Test run:
Output:
我没有找到一种方法可以轻松做到这一点,并且 ruby/rails 代码来实现它非常简单。那么为什么不自己做一个辅助方法呢?您的方法的签名可以是:
因此,通过调用(以 HAML 方式)
您应该得到您想要的。
I don't see a way to do that easily, and the ruby / rails code to get it is pretty simple. So why not doing a helper method on your own? The signature for your method could be:
So by calling (in a HAML way)
you should get what you want.